All rights are reserved by Niteesh Kumar.. Theme images by Storman. Powered by Blogger.

Program to sort a number of words using merge sort.

OBJECTIVE-Write a C program to Sort the N Names in an Alphabetical Order.
ALGORITHM-
-Start from the first name and compare it with all other names
-if it is lexicographically large from others then swap both of them
-Repeat this process for n-1 names

CODE-

`#include<stdio.h>#include<stdlib.h>#include<string.h>#include<time.h>void merge(char a[][30],long int l,long int m,long int r){    long int i,j,k;    long int n1=m-l+1;    long int n2=r-m;    char la[n1][30],ra[n2][30];    for(i=0;i<n1;i++)    strcpy(la[i],a[l+i]);    for(j=0;j<n2;j++)    strcpy(ra[j],a[m+1+j]);    i=0;j=0;k=l;    while(i<n1 && j<n2)    {        if(strcmp(la[i],ra[j])<0)        {            strcpy(a[k],la[i]);            i++;            k++;        }        else        {            strcpy(a[k],ra[j]);            j++;            k++;        }    }    while(i<n1)    {        strcpy(a[k],la[i]);        i++;        k++;    }    while(j<n2)    {            strcpy(a[k],ra[j]);            j++;            k++;    }}void mergesort(char a[][30],long int l,long int r){    if(l<r)    {        int m=l+(r-l)/2;        mergesort(a,l,m);        mergesort(a,m+1,r);        merge(a,l,m,r);    }}int main(){    int n,i,j;    printf("enter number of inputs:");    scanf("%d",&n);    char a[n][30],temp[n];    for(i=0;i<n;i++)        scanf("%s",a[i]);    mergesort(a,0,n-1);        printf("after sorting:\n");    for(i=0;i<n;i++)        printf("%s\n",a[i]);return 0;}`

INPUT-
11
niteesh
ravi
ujjwal
vivek
zafar
nitin
jatin
deepak
ashish
shubham
anuj

OUTPUT-
anuj
ashish
deepak
jatin
niteesh
nitin
ravi
shubham
ujjwal
vivek
zafar