#include <iostream>
#include<math.h>
using namespace std;
void merge(int *a, int low, int mid, int high){
int *b = new int[ high - low + 2 ];
b[0] = high - low + 1;
int j = mid + 1;
int i;
int k = low;
for(i = 1; k <= mid && j <= high; i++){
if(a[k] < a[j])
b[i] = a[k++];
else
b[i] = a[j++];
}
while(k <= mid) b[i++] = a[k++];
while(j <= high) b[i++] = a[j++];
for(int i = 1; i <= b[0]; i++)
a[low+i-1] = b[i];
}
void mergeSort(int *a, int low, int high){
if(low < high){
int mid = low + (high - low) / 2;
mergeSort(a, low, mid);
mergeSort(a, mid+1, high);
merge(a, low, mid, high);
}
}
int main()
{
int n;
cout << "输入无序数组的个数 :" << endl;
cin >> n;
int *a = new int[n+1];
a[0] = n;
for(int i = 1; i <= a[0] ; i++){
cin >> a[i];
}
//归并排序
mergeSort(a, 1, a[0]);
for(int i = 1; i <= a[0]; i++){
cout << a[i] << " " ;
}
cout << endl;
return 0;
}
时间复杂度 O(n^log n)以2 为底
空间 O(n)