c-归并排序

归并排序(MERGE-SORT)是建立在归并操作上的一种有效的排序算法,该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。

简单的说来归并排序算法,就是相当于将一个数组分为两个有序数列,然后再将其有序合并起来,当然这是指的最后一步,那么如何得到这两个序列呢,又可以将两个序列各自在分成两个序列,最后你发现一个数做为一个序列了,这不就是典型的递归么?理解上面应该不难,那么还是得靠自己想清楚。以下代码参考了白话经典算法,上次给大家发的pdf。

#include <stdio.h>
#include <stdlib.h>
//合并两个序列
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);
    }
}
void main()
{
    int temp[10]={0};
    int a[10]={2,6,8,4,1,3,7,9,5,0};
    mergesort(a,0,10-1,temp);
    for(int i=0;i<10;i++)
    {
        printf("%d",a[i]);
    }
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注