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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
|
#include <iostream>
using namespace::std;
void print(int* r, int length)
{
for(int i=0; i<length; i++)
{
cout << r[i] << endl;
}
}
int* merge(int* a, int* b, int alen, int blen)
{
int i=0;
int j=0;
int dev[alen+blen+1];
int* ans= dev;
int k=0;
print(a,alen);
while((i<alen)&&(j<blen))
{
if(a[i]<=b[j])
{
ans[k]=a[i];
i++;
k++;
}
else
{
ans[k]=b[j];
j++;
k++;
}
}
if(i>=alen)
{
while(k<(alen+blen))
{
ans[k]=b[j];
j++;
}
}
else if(j>=blen)
{
while(k<(alen+blen))
{
cout << ans[k]<< endl;
ans[k]=a[i];
i++;
}
}
return ans;
}
int* mergesort(int* a, int len)
{
if(len!=1)
{
int firsthalf=(len/2);
int secondhalf= (len-firsthalf);
int* b=mergesort(a,firsthalf);
int* c=mergesort(a+firsthalf,secondhalf);
int* ans= merge(b,c,firsthalf,secondhalf);
return ans;
}
else{
return a;
}
}
int main()
{
int b[10]={10,9,8,7,6,5,4,3,2,1};
print(b,10);
int* c=mergesort(b, 10);
for(int i=0; i<10; i++)
{
cout << "" << endl;
}
print(c,10);
return 0;
}
|