1. 程式人生 > >分治法之合併排序(C實現)

分治法之合併排序(C實現)

#include <stdio.h>
 
void merge(int a[],int p,int q,int r)
{
    int n1=q-p+1,n2=r-q;
    int b1[n1];
    int b2[n2];
    int i=0,j=0,temp1=p,temp2=q;
    while(p<=q)
    {
        b1[i]=a[p];
        ++i;
        ++p;
    }
    while(q+1<=r)
    {
        b2[j]=a[q+1];
        ++j;
        ++q;
    }
 
    p=temp1;q=temp2;
    i=0,j=0;
    while(p<=r)
    {
        if(i==n1)         
        {
            a[p]=b2[j];
            ++j;
        }
        else if(j==n2)
        {
            a[p]=b1[i];
            ++i;
        }
     
        else if(b1[i]<b2[j])
        {
            a[p]=b1[i];
            ++i;
        }
        else
        {
            a[p]=b2[j];
            ++j;
        }
        ++p;
    }
}
 
void merge_sort(int a[],int p,int r)
{
    int q=0;
    if(p<r)
    {
        q=(p+r)/2;
        merge_sort(a,p,q); 
        merge_sort(a,q+1,r);
        merge(a,p,q,r);
    }
}
 
int main()
{
    int i, a[100];
    srand(time(0));
    for ( i = 1; i < 101; ++i ){
        a[i-1] = rand() % 1001;
        printf( "%3d ", a[i-1] );
        if(i%15==0) printf("\n"); 
    }
    printf("\n\n");
    SelectionSort(a, 100);
    for ( i = 1; i < 101; ++i ){
        printf( "%3d ", a[i-1] );
        if(i%15==0) printf("\n"); 
    }
    getch();
    return 0;
}

執行效果圖