基本思想:归并(Merge)排序法是将两个(或两个以上)有序表合并成一个新的有序表,即把待排序序列分为若干个子序列,每个子序列是有序的。然后再把有序子序列合并为整体有序序列。
代码:
#include<stdio.h>
#include<windows.h>
void merge_array(int *arr,int low,int mid,int high)
{
int k,i;
int *temp = (int *)malloc((high-low+1)*sizeof(int));
int left_low = low;
int left_high = mid;
int right_low = mid + 1;
int right_high = high;
for(k=0;left_low<=left_high && right_low<=right_high;k++)
{
if(arr[left_low]<=arr[right_low])
{
temp[k] = arr[left_low++];
}else
{
temp[k] = arr[right_low++];
}
}
if(left_low<=left_high)
{
for(i=left_low;i<=left_high;i++)
{
temp[k++] = arr[i];
}
}
if(right_low<=right_high)
{
for(i=right_low;i<=right_high;i++)
{
temp[k++] = arr[i];
}
}
for(i=0;i<high-low+1;i++)
{
arr[low+i] = temp[i];
}
free(temp);
return;
}
void merge_sort(int *arr,int first,int last)
{
int mid = 0;
if(first<last)
{
mid = (first+last)/2;
merge_sort(arr,first,mid);
merge_sort(arr,mid+1,last);
merge_array(arr,first,mid,last);
}
return;
}
int main()
{
int a[] = {49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,56,17,18,23,34,15,35,25,53,51};
int n= 28;
int i;
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
printf("\n\n");
merge_sort(a,0,n-1);
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
printf("\n");
system("pause");
return 0;
}