1. 程式人生 > >歸併排序(C語言)

歸併排序(C語言)

#include <stdio.h>
#include <stdlib.h>
#define N 10

void Merge(int a[],int l,int m,int h)
{
    int i;
    int j;
    int k;
    int n1 = m - l + 2;
    int n2 = h - m + 1;
    int left[n1];
    int right[n2];
    for (i = 0;i < n1-1;i++)
        left[i] = a[l+i];
    left[i] = 100000;
    for (j = 0;j < n2-1;j++)
        right[j] = a[m+j+1];
    right[j] = 100000;
    i = j = 0;
    for (k = l;k <= h;k++)
    {
        if (left[i] < right[j])
        {
            a[k] = left[i];
            i++;
        }
        else
        {
            a[k] = right[j];
            j++;
        }
    }
}

void Merge_sort(int a[],int l,int h)
{
    int m;
    if (l < h)
    {
        m = (l + h) / 2;
        Merge_sort(a,l,m);
        Merge_sort(a,m+1,h);
        Merge(a,l,m,h);
    }
}

void print(int a[],int n)
{
    int i;
    for (i = 0;i < n;i++)
        printf("%d\t",a[i]);
}

int main()
{
    int a[N] = {1,3,5,7,9,2,4,6,8,10};
    print(a,N);
    printf("\n\n");
    Merge_sort(a,0,9);
    print(a,N);
}