稳定 O(nlogn)
#include <stdio.h>
#include <stdlib.h>void ArrayCopy(int a[], int b[], int low, int high) {
while (low <= high) {
a[low] = b[low];
++low;
}
}
void Merge(int a[], int b[], int low, int mid, int high) {
int j = mid + 1;
int k = low; //b数组自增下标
int i = low;
while ((low <= mid) && (j <= high)) {
if (a[low] < a[j]) {
b[k++] = a[low++];
}
else {
b[k++] = a[j++];
}
}
if (j <= high) { //左半部分都进入b数组,把剩余的右半部分加入到b数组
while (j <= high) {
b[k++] = a[j++];
}
}
if (low <= mid) { //右半部分都进入b数组,把剩余的左半部分加入到b数组
while (low <= mid) {
b[k++] = a[low++];
}
}
ArrayCopy(a, b, i, high);
}
void MergeSort(int a[], int b[], int low, int high) {
int mid = 0;
if (low == high) {
b[low] = a[low];
return;
}
else {
mid = (low + high) / 2;
MergeSort(a, b, low, mid);
MergeSort(a, b, mid + 1, high);
Merge(a, b, low, mid, high);
}
}
int main() {
int i = 0;
int a[] = {1, 2, 3, 5, 4, 78, 56, 9, 87, 10};
int b[10] = {0};
printf("排序前: ");
for (i = 0; i < sizeof(a)/sizeof(a[0]); i++)
printf("%d ", a[i]);
printf("\n");
MergeSort(a, b, 0, sizeof(a)/sizeof(a[0])-1);
printf("排序后: ");
for (i = 0; i < sizeof(a)/sizeof(a[0]); i++)
printf("%d ", b[i]);
printf("\n");
return 0;
}