算法时间复杂度: O(n*log2 n)
空间复杂度:O(n)
算法稳定性:稳定
//合并两个有序数组
void merge(int a[],int b[],int low, int mid, int high){
int i, j, k;
for (k = low; k <= high; k++) {
b[k] = a[k];
}
for (i = low, k = low, j = mid + 1; i <= mid && j <= high; k++) {
if (b[i] <= b[j])
a[k] = b[i++];
else
a[k] = b[j++];
}
while (i <= mid) a[k++] = b[i++];
while (j <= high) a[k++] = b[j++];
}
//递归进行归并排序,这里传参数b的原因是因为c语言没法在创建全局变量时使用malloc函数
void mergeSort(int a[], int b[], int low, int high) {
if (low < high) {
int mid = (low + high) / 2;
mergeSort(a, b, low, mid);
mergeSort(a, b, mid + 1, high);
merge(a, b, low, mid, high);
}
}
int main() {
int a[10] = { 4,7,2,9,4,0,6,1,2,6 };
int b[10];
mergeSort(a, b, 0, 9);
for (int i = 0; i < 10; i++) {
printf("%d ", a[i]);
}
}