归并排序

来源:互联网 发布:seo关键词优化外包 编辑:程序博客网 时间:2024/06/16 06:18

时间复杂度为:O(nlogn)
归并排序(MERGE-SORT)是建立在归并操作上的一种有效的排序算法,该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。若将两个有序表合并成一个有序表,称为二路归并。

具体实现(c):
递归实现:

//将有二个有序数列a[first…mid]和a[mid…last]合并。

void mergesort(int a[], int first, int last, int temp[]);
void mergearray(int a[], int first, int mid, int last, int temp[]);
int main()
{
int a[10] = {18, 4,6,71,11,10,9,2,52,33};
int temp[10];
mergesort(a,0, 10, temp);
}
void mergearray(int a[], int first, int mid, int last, int temp[])
{
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 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, mid, last, temp); //再将二个有序数列合并

    int l;    for(l = 0; l<10;l++)    {        printf("-%d", temp[l]);    }    printf("----------\n");}

}

0 0