归并算法的思想:把待排序的文件分为若干个子文件,先将每个子文件内的记录排序,再将已排序的子文件合并,得到完全排序的文件。
首先,先将数组拆分为若干子文件,一分为二,再分为四,等等。
//拆分数组
void margeSort(int a[],int left,int right)
{
if(left>=right)
{
return ;
}
else
{
int mid = (left+right)/2;
mergeSort(a,left,mid);
mergeSort(a,mid+1,right)
merge(a,left,mid,right);
}
}
其次,就是将已排好序的数组合并。
//合并已排好序的数组 left 是0 right是 n-1
void merge(int a[],int left,int mid,int right)
{
int s1 = left;//拆分的第一个数组的指针
int s2 = right;//拆分的第二个数组的指针
int temp[right-left+1];//设立一个中间数组,为后面复制数组提供
int i=0;//为 temp 所用
while(s1<=mid && s2<=right)
{
if(a[s1]<=a[s2])
{
temp[i] = a[s1];
i++;
s1++;
}
else
{
temp[i] = a[s2];
i++;
s2++;
}
}
//当 s1 还有剩余时
while(s1 <= mid)
{//由于我们的数组都是有序的,所以直接在后面加就好
temp[i] = a[s1];
i++;
s1++;
}
//当 s2 还有剩余时
while(s2 <= mid)
{//由于我们的数组都是有序的,所以直接在后面加就好
temp[i] = a[s2];
i++;
s2++;
}
//最后将数组复制回去
for(int j = 0; j < right-left+1 ; j++)
{
a[j+left] = temp[j];
}
```