归并排序是一个机遇分治的比较算法。当我们有一个非常大的列表需要排序,将列表分成两个子列表,然后在排序会好些。如果等分后还是很大,我就继续分割,直到可以很简单的排序为止。
归并排序的复杂度不是很高。在最差的时候也是O(nlongn).(快排最差的时候是O(n^2).
其中关键的有两部分。一个是两个有序数组的合并。另一个是分治(把大数组分成小数组,用递归,条件是first<last)
代码如下:
#include <iostream>
using namespace std;
void mergearray(int a[],int first,int last,int temp[])
{
int mid=(first+last)/2;
int i=first;int j=mid+1;
int k=0;
while (i<=mid&&j<=last)
{
if(a[i]<a[j])
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}
while (i<=mid)
temp[k++]=a[i++];
while (j<=last)
temp[k++]=a[j++];
for (int i=0;i<k;i++)
a[i+first]=temp[i]; //这个地方很关键
}
void mergesort(int a[], int first, int last, int temp[])
{
if (first < last)
{
int mid = (first + last) / 2;
mergesort(a, first, mid, temp); //左边有序
mergesort(a, mid + 1, last, temp); //右边有序
mergearray(a, first, last, temp); //再将二个有序数列合并
}
}
bool MergeSort(int a[], int n)
{
int *p = new int[n];
if (p == NULL)
return false;
mergesort(a, 0, n - 1, p);
delete[] p;
return true;
}
int main()
{
int a[]={4,10,6,8};
int temp[4];
//mergearray(a,0,3,temp);
MergeSort(a,4);
for (int i=0;i<4;i++)
{
cout << a[i] <<endl;
}
return 0;
}