1. 归并排序
//归并排序(递归 归并,每个子问题都是对两个有序的子序列合并)
void MERGR(int* arr, int len, int low, int mid, int high) {
int* b = new int[high-low+1]; // 归并排序的空间复杂度 O(n)
int left = low;
int right = mid + 1;
int i = 0;
while (left <= mid && right <= high) {
if (arr[right] < arr[left]) {
b[i++] = arr[right++];
}
else {
b[i++] = arr[left++];
}
}
//有剩余的组直接接入已排序列后
while (left <= mid)
b[i++] = arr[left++];
while (right <= high)
b[i++] = arr[right++];
//拷贝到arr的指定区间
for (int j = low; j <= high; j++)
arr[j] = b[j-low];
// display(arr, len);
}
void MERGEsort(int* arr, int len, int low, int high) {
if (low < high) {
int mid = (low + high) / 2;
MERGEsort(arr, len, low, mid); //已有序的左序列
MERGEsort(arr, len, mid + 1,high); //已有序的右序列
MERGR(arr, len, low, mid, high); //归并
}
}