核心思路: 先分段排序,再归并,再复制到原来数组中。 优质代码:? ?
void merge(int arr[], int L, int M, int R);
void process(int arr[], int L, int R);
void mergeSort(int arr[], int sz) {
if (arr == NULL || sz < 2)
return;
process(arr, 0, sz - 1);
}
void process(int arr[], int L,int R) {
if (L == R)
return;
int M = L + (R - L) / 2;
process(arr, L, M);
process(arr, M + 1, R);
merge(arr, L, M, R);
}
void merge(int arr[], int L, int M, int R) {
int help[]= new int[R - L + 1];
int i = 0;
int p1 = L, p2 = M + 1;
while (p1 <= L && p2 <= R)
help[i++] = arr[p1] > arr[p2] ? arr[p2++] : arr[p1++];
while (p1 <= L)
help[i++] = arr[p1++];
while (p2 <= R)
help[i++] = arr[p2++];
for (int j = 0;j < i;j++)
arr[j+L] = help[j];
}
|