Friday, March 21, 2014

merge sort + quick sort

1. Merge Sort:
void merge(int a[], int low, int mid, int high)
{
    int b[10000];    //initial enough large space! >= length of array a[].
    int i = low, j = mid + 1, k = 0;

    while (i <= mid && j <= high) {
        if (a[i] <= a[j])
            b[k++] = a[i++];
        else
            b[k++] = a[j++];
    }
    while (i <= mid)
        b[k++] = a[i++];

    while (j <= high)
        b[k++] = a[j++];

    k--;   //Very important!
    while (k >= 0) {
        a[low + k] = b[k];
        k--;
    }
}

void mergesort(int a[], int low, int high)
{
    if (low < high) {
        int m = (high + low)/2;
        mergesort(a, low, m);
        mergesort(a, m + 1, high);
        merge(a, low, m, high);
    }
}



2. Quick Sort:

int divide(int * arr, int length, int pivot) {
    int target = arr[pivot];
    swap(arr+length-1, arr+pivot);
    pivot = 0;
    int idx = 0;

    while(idx < length-1) {
if(arr[idx] <= target) {
   swap(arr+idx, arr+pivot);
   pivot++;
}
idx++;
    }
    swap(arr+length-1, arr+pivot);
    return pivot;
}

void qsort(int * arr, int length, int pivot) {
    if(length <= 1) return;
    assert(pivot<length && pivot>=0);
    pivot = divide(arr, length, pivot);
    qsort(arr, pivot, 0);
    qsort(arr+pivot+1, length-pivot-1, 0);
}

void sort(int * arr, int size) {
    qsort(arr,  size, 0);
}

No comments:

Post a Comment