Step in detail:
a. Divide array into halves.
b. Recursively sort each half.
c. Merge two halves.
Input: earfk
Output:a e f k r
//MERGESORT with C
#include<stdio.h>
#define MAX 5
int less(char x,char y)
{
if(x<=y)
return 1;
else
return 0;
}
void merge(char a[],char temp[],int lo,int mid,int hi)
{
int i,j,k;
for(k=lo;k<=hi;k++)
temp[k]=a[k];
i=lo;j=mid+1;
for(k=lo;k<=hi;k++)
{
if(i>mid)
a[k]=temp[j++];
else if(j>hi)
a[k]=temp[i++];
else if(less(temp[i],temp[j]))
a[k]=temp[i++];
else
a[k]=temp[j++];
}
}
void sort(char a[],char temp[],int first,int end)
{
int mid;
if(first==end)
return;
mid=first+(end-first)/2;
sort(a,temp,first,mid);
sort(a,temp,mid+1,end);
merge(a,temp,first,mid,end);
}
int main()
{
int i;
char a[MAX],temp[MAX];
for(i=0;i<MAX;i++)
scanf("%c",&a[i]);
sort(a,temp,0,MAX-1);
for(i=0;i<MAX;i++)
printf("%c ",a[i]);
return 0;
}