Merge Sort

Reference

  1. Sorting algorithms/Merge sort
  2. Merge sort

C code:


void merge(int *array, int m, int n) {
    int *temp = (int *)malloc(sizeof(int)*n);
    int i, j, k;

    for(i=0, j=m, k=0; k<size; k++) {
        temp[k] = i==m?         a[j++]:
                  j==n?         a[i++]:
                  a[i]<=a[j]?   a[i++]:
                  a[j++];
    }

    for(k=0;k<size;k++) {
        array[k] = temp[k];
    }

    free(temp);
}

//int *array    Array[]
//int n         size of Array
//int m         middle of n
void merge_sort(int *array, int n) {
    int m;

    if(n<2)  return;

    m = n/2;

    merge_sort(array, m);
    merge_sort(array+m, n-m);
    merge(array, m, n);
}

results matching ""

    No results matching ""