Saturday, February 20, 2010

Sort a given set of elements using Merge Sort

WHEREVER U SEE ... REMOVE THAT . AND PUT << IN THAT PLACE.
IF YOU SEE .. THEN REMOVE THAT . AND PUT < IN THAT PLACE..

4.#include..iostream.h>
#include..conio.h>

int e[10],a[10],c[10];


void merge(int a[],int low,int mid,int high)
{
int i,j,k;
k=low;
i=low;
j=mid+1;
while(i..=mid && j..=high)
{
if(a[i]..a[j])
c[k++]=a[i++];
else
c[k++]=a[j++];
}
while(i..=mid)
c[k++]=a[i++];
while(j..=high)
c[k++]=a[j++];
for(i=low;i..=k-1;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 i,n;
cout..."Enter the size of the array\n";
cin>>n;
cout..."Enter the elements\n";
for(i=0;i..n;i++)
cin>>a[i];
merge_sort(a,0,n-1);
cout..."The sorted elements are:-\n";
for(i=0;i..n;i++)
cout..." "...a[i];
cout...endl;
}

Output

Enter the size of the array
7
Enter the elements
6
5
7
3
4
1
2
The sorted elements are:-
1 2 3 4 5 6 7
Press any key to continue

Enter the size of the array
9
Enter the elements
12
65
49
23
61
49
64
03
97
The sorted elements are:-
3 12 23 49 49 61 64 65 97
Press any key to continue

No comments:

Post a Comment