1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
#include<iostream.h>
#include<conio.h>
#include<process.h>
void msort(int arr[],int start,int end);
void merge(int arr[],int start,int half,int end);
void main()
{
clrscr();
int arr[20]={22,33,11,10,9,8,7,77,45};
int end=9;
int start=1;
msort(arr,start,end);
for(int i=1;i<=9;i++)
cout<<arr[i]<<"/n";
getch();
}
void msort(int arr[],int start,int end)
{ int half;
if(start==end)
return;
half=(start+end)/2;
msort(arr,start,half);
msort(arr,half+1,end);
merge(arr,start,half,end);
}
void merge(int arr[],int start,int half,int end)
{int n1,n2,j,k, i;
int left[20],right[20];
n1=half-start+1; n2=end-half;
for(i=1;i<=n1;i++) // now i have declaer outside of for ..
left[i]=arr[start+i-1];
for(i=1;i<=n2;i++)
right[i]=arr[half+i];
i=j=1; k=start;
while(i<=n1&&j<=n2)
{
if(left[i]<=right[i])
{
arr[k]=left[i];
i++;
}
else
{
arr[k]=right[j];
j++;
}
k++;
}
if(i<=n1)
{
while(i<=n1)
{ arr[k]=left[i];
i++;
j++;}
}
else
{
while(j<=n2)
arr[k]=right[j];
j++;
k++;
}
}
|