基本排序算法实现

一些基本排序算法的C实现

void Swap(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

#pragma mark - Bubble

void BubbleSort(int a[], int n)
{
    int i, j, temp;
    for (j = n-1; j > 0; j--) {
        for (i = 0; i < j; i++) {
            if (a[i]>a[i+1]) {
                temp = a[i+1];
                a[i+1] = a[i];
                a[i] = temp;
            }
        }
    }
}

#pragma mark - Insert & Shell

void InsertSort(int a[], size_t n)
{
    int i, j;
    for (i = 1; i < n; i++)
        for (j = i - 1; j >= 0 && a[j] > a[j + 1]; j--)
            Swap((a+j), (a+ j + 1));
}

void ShellSort(int data[], int size)
{
    for (int gap = size / 2; gap > 0; gap /= 2)
        for (int i = gap; i < size; ++i)
            for (int j = i-gap; j >= 0 && data[j] > data[j+gap]; j -= gap) {
                Swap(data + j, data + j + gap);
            }
}

#pragma mark - Quick

int Partition(int a[], int low, int high)
{
    int t = a[low];
    while (low < high) {
        while (low < high && a[high] >= t)
            high--;
        
        a[low] = a[high];
        
        while (low < high && a[low] <= t)
            low++;
        
        a[high] = a[low];
    }
    
    a[low] = t;
    
    return low;
}

void QuickSort(int a[], int low, int high)
{
    if (low >= high) {
        return;
    }
    
    int pivotloc = 0;
    pivotloc = Partition(a, low, high);
    QuickSort(a, low, pivotloc-1);
    QuickSort(a, pivotloc, high);
}

#pragma mark - Merge

void Merge(int unsorted[], int first, int mid, int last, int sorted[])
{
    int i = first, j = mid;
    int k = 0;
    while (i < mid && j < last)
        if (unsorted[i] < unsorted[j])
            sorted[k++] = unsorted[i++];
        else
            sorted[k++] = unsorted[j++];
    
    while (i < mid)
        sorted[k++] = unsorted[i++];
    while (j < last)
        sorted[k++] = unsorted[j++];
    
    for (int v = 0; v < k; v++)
        unsorted[first + v] = sorted[v];
}

void MergeSort(int unsorted[], int first, int last, int sorted[])
{
    if (first + 1 < last)
    {
        int mid = (first + last) / 2;
        MergeSort(unsorted, first, mid, sorted);
        MergeSort(unsorted, mid, last, sorted);
        Merge(unsorted, first, mid, last, sorted);
    }
}

 

posted @ 2014-04-04 11:46  馒不头  阅读(142)  评论(0编辑  收藏  举报