点击查看代码
//Merge sort
#include<iostream>
using namespace std;
void merge(int L[], int R[], int A[], int nL, int nR) {//将两个已排序数组合并填入
int i = 0, j = 0, k = 0;//i,j为未拾取元素索引,k为归并数组索引
while (i < nL && j < nR) {
if (L[i] < R[j]) {
A[k] = L[i];
i++;
}
else {
A[k] = R[j];
j++;
}
k++;
}//在两个数组中选取未拾取元素最小者填入归并数组
while (i < nL) {
A[k] = L[i];
i++;
k++;
}
while (j < nR) {
A[k] = R[j];
j++;
k++;
}//有剩余元素数组全部填入
}
void mergesort(int A[], int n) {
if (n < 2) return;//中止条件
int mid = n / 2;//从中间分为两组
int* L = new int[mid];
int* R = new int[n - mid];//动态分配
for (int i = 0; i < mid; i++) L[i] = A[i];//左边填入
for (int i = mid; i < n; i++) R[i - mid] = A[i];//右边填入
mergesort(L, mid); // sorting the left subarray
mergesort(R, n - mid); // sorting the right subarray
merge(L, R, A, mid, n - mid);//归并填入
delete []L;
delete []R;//不要忘记删除动态内存
}//时间复杂度:O(nlogn)
//空间复杂度:O(n)
int main() {
int A[] = { 2,7,4,1,5,3 };
mergesort(A, 6);
for (int i = 0; i < 6; i++) cout << A[i] << " ";
cout << endl;
}