【数据结构】归并排序
发布时间:2021-05-19 22:47:09 所属栏目:安全 来源:网络整理
导读:归并排序(Merge sort,台湾译作:合并排序)是建立在归并操作上的一种有效的排序算法。该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。(维基百科) 参考文章: http://www.voidcn.com/article/p-ccwctxoe-yt.html 下面是具体代码: #in
|
归并排序(Merge sort,台湾译作:合并排序)是建立在归并操作上的一种有效的排序算法。该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。(维基百科) 参考文章: http://www.voidcn.com/article/p-ccwctxoe-yt.html 下面是具体代码: #include <stdio.h>
#define true 1
#define false 0
//将有二个有序数列a[first...mid]和a[mid...last]合并。
void mergearray(int a[],int first,int mid,int last,int temp[])//first,mid,last均为下标
{
int i = first,j = mid + 1;
int m = mid,n = last;
int k = 0;
while (i <= m && j <= n)
{
if (a[i] < a[j])
temp[k++] = a[i++];
else
temp[k++] = a[j++];
}
while (i <= m)
temp[k++] = a[i++];
while (j <= n)
temp[k++] = a[j++];
for (i = 0; i < k; i++)
a[first + i] = temp[i];
}
void mergesort(int a[],int temp[])
{
if (first < last)
{
int mid = (first + last) / 2;
mergesort(a,first,temp); //递归使得左边有序
mergesort(a,mid + 1,last,temp); //递归使得右边有序
mergearray(a,temp); //再将二个有序数列合并
}
}
int MergeSort(int a[],int n)
{
//int *p = new int[n];
int * p = (int *)malloc( n*sizeof(int) );
if (p == NULL)
return false;
mergesort(a,n - 1,p);
//delete[] p;
free(p);
return true;
}
int main()
{
int i;
int a[]={23,4,9,34,12,3,89,7,80};
MergeSort(a,9);
for(i=0; i<9; i++)
printf("%d ",a[i]);
printf("n");
return 0;
}
(编辑:新余站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
站长推荐


