3.归并排序:稳定排序,时间复杂度最差、最好、平均为O(n log n),空间复杂度为O(n)
#include <iostream>
using namespace std;
// 二路归并(可以理解为两个有序数组的合并)
void merge(int *a,int low, int mid, int high)
{
int *A = a + low;
int lb = mid - low;
int *B = new int[lb]; // 开辟一个临时数组,存储前半部数组
for (int i = 0; i < lb; i++)
B[i] = A[i];
int lc = high - mid;
int *C = a + mid; // 后半部子数组
int i = 0, j = 0, k = 0;
while (i < lb && j < lc)
{
if (B[i] <= C[j])
A[k++] = B[i++];
else
A[k++] = C[j++];
}
while (i < lb)
{
A[k++] = B[i++];
}
while (j < lc)
{
A[k++] = C[j++];
}
/*
书上的
for (int i = 0, j = 0, k = 0; (j < lb) || (k < lc);)
{
if ((j < lb) && (!(k < lc) || (B[j] <= C[k])))
A[i++] = B[j++];
if ((k < lc) && (!(j < lb) || (C[k] < B[j])))
A[i++] = C[k++];
}*/
delete[]B;
}
void merge_sort(int *a, int low, int high)
{
if (high - low < 2)
return;
int mid = (low + high) / 2;
merge_sort(a,low, mid); // 第一轮递归结束之后,变成了6
merge_sort(a,mid, high); // 第一轮递归结束之后,变成了3
merge(a, low, mid, high); // 归并的时候排序
}
int main()
{
int a[] = { 6,3,2,7,1,5,8,4 };
int N = sizeof(a) / sizeof(int);
merge_sort(a, 0, N);
for (int i = 0; i < N; i++)
cout << a[i] << " ";
return 0;
}
排序过程: