在C中打印合并排序的每个步骤

时间:2017-04-27 20:26:44

标签: c mergesort array-merge

有些我对C代码很陌生,我想知道如何打印合并排序的每一步。

例如,我的未排序数组是(2,9,4,6,8,5)。然后我想打印出First Half is 2, 9, 4然后打印Second half is 6, 8, 5

然后对每一半进行排序,并打印First half sorted is 2, 4, 9Second half sorted is 5, 6, 8

最后显示排序列表Sorted array is 2, 4, 5, 6, 8, 9

这是我的代码:

//Splitting the array into 2
void merge(int arr[], int lhs, int mid, int rhs) {
int i, j, k;
int half1 = mid - lhs + 1;
int half2 = rhs - mid;

int first[half1], second[half2]; //Temporary arrays

for (i = 0; i < half1; i++) {
    first[i] = arr[lhs + i];
}

for (j = 0; j < half2; j++) {
    second[j] = arr[mid + 1 + j];
}

i = 0;
j = 0;
k = lhs;

while (i < half1 && j < half2) {

    if (first[i] <= second[j]) {
        arr[k] = first[i];
        ++i;
    } else {
        arr[k] = second[j];
        j++;
    }

    k++;
}

while (i < half1) {
    arr[k] = first[i];
    i++;
    k++;
}

while (j < half2) {
    arr[k] = second[j];
    j++;
    k++;
}
}


//Merge Sorting
void merge_sort(int arr[], int l, int r) {
if (l < r) {
    int midd = (l + (r-1))/ 2;
    merge_sort(arr, l, midd);
    merge_sort(arr, midd+1, r);
    merge(arr, l, midd, r);
   }
}

0 个答案:

没有答案