百度了一下,什么叫归并排序。
归并排序(MERGE-SORT)是建立在归并操作上的一种有效的排序算法,该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。若将两个有序表合并成一个有序表,称为二路归并。
关于归并排序的具体实现过程,说起来很麻烦,就用一张图简单明白的看出来就好了,话不多说,上图:
#include<bits/stdc++.h>
using namespace std;
const int N = 100001;
int temp[N];
/*
将一个数组分成两段再按顺序归并到一个新的temp数组中
*/
void Merge(int *a,int low,int mid,int high,int *temp) {
int i,j,k;
i = low;
j = mid+1;
k = 0;
while (i<=mid&&j<=high) {
if(a[i]<=a[j])
temp[k++] = a[i++];
else
temp[k++] = a[j++];
}
while (i<=mid) //把剩下没弄完的搞进去
temp[k++] = a[i++];
while (j<=high)
temp[k++] = a[j++];
for(i=0;i<k;i++) //temp赋值给a
a[low+i] = temp[i];
}
/*
两路归并
*/
void MergeSort (int *a,int low,int high,int*temp) {
if(low<high){
int mid = (low+high)/2;
MergeSort(a,low,mid,temp);
MergeSort(a,mid+1,high,temp);
Merge(a,low,mid,high,temp);
}
}
/*
主函数
*/
int main () {
int a[] = {2,23,34,43,45,6,7,8,5,4,56,78};
MergeSort(a,0,11,temp);
for (int i = 0; i <=11 ; i++)
{
cout<<a[i]<<' ';
}
cout<<endl;
return 0;
}
时间效率: O(nlog2n)
空间效率: O(n)
稳定性: 稳定