5/01/2009

C Program Merge Sort


/*C Program Merge Sort*/
#include<stdio.h>
#include<conio.h>
void merge(int a[10],int low,int mid,int high)
{
    int i=low;
    int j=mid+1;
    int k=low;
    int c[100];
    while(i<=mid&&j<=high)
    {
        if(a[i]<a[j])
        {
            c[k]=a[i];
            i=i+1;
            k=k+1;
        }
        else
        {
            c[k]=a[j];
            j=j+1;
            k=k+1;
        }
    }
    while(i<=mid)
    {
        c[k]=a[i];
        k=k+1;
        i=i+1;
    }
    while(j<=high)
    {
        c[k]=a[j];
        k=k+1;
        j=j+1;
    }
    for(i=low; i<=high; i++)
    {
        a[i]=c[i];
    }
}
void merge_sort(int a[],int low,int high)
{
    int mid;
    if(low<high)
    {
        mid=(low+high)/2;
        merge_sort(a,low,mid);
        merge_sort(a,mid+1,high);
        merge(a,low,mid,high);
    }
}
void main()
{
    int a[100],n,i;

    printf("Enter number of elements: \n");
    scanf("%d",&n);
    printf("enter the elements:\n");
    for(i=0; i<n; i++)
        scanf("%d",&a[i]);
    merge_sort(a,0,n-1);
    printf("sorted elements are:\n");
    for(i=0; i<n; i++)
        printf("%d\n",a[i]);

}
Out Put:
Enter number of elements:
9
enter the elements:
12
56
4
8749
32
48
2
15
98
sorted elements are:
2
4
12
15
32
48
56
98
8749

No comments:

Post a Comment