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
|
// Main function of the C++ program.
#include <iostream>
using namespace std;
void printarray(int a[],int size);
void splitsort(int b[], int start, int end); //Split array into half
void merge(int b[], int start, int end); // merge the sorted arrays
int main()
{
cout<<"This is merge sort"<<endl;
int array[]={9,8,7,6,5,4,3,2,1};
int length=sizeof(array) / sizeof(array[0]);
printarray(array,length);
splitsort(array,0,length-1);
cout<<"sorted array"<<endl;
printarray(array,length);
return 0;
}
void printarray(int a[],int size){
for(int i=0;i<size;i++){
cout<<a[i]<<",";
}
cout<<endl;
return;
}
void splitsort(int b[], int start, int end){
//base case
if(end==start){return;}
//
splitsort(b,start,(start+end)/2);
splitsort(b,(start+end)/2+1,end);
merge(b,start,end);
return;
}
void merge(int b[], int start, int end){
int tempb[(end-start)+1];
//base case
if (end==start){return;} // if single element being merged
int i=start;
int j=(start+end)/2+1;
for(int k=start;k<=end;k++){
if(i==(start+end)/2+1){tempb[k]=b[j];j++;}// finished first array
else if(j==end+1){tempb[k]=b[i];i++;}// finished second array
else if (b[i]>=b[j]){
tempb[k]=b[j];
j++;
}
else if(b[j]>=b[i]) {
tempb[k]=b[i];
i++;
}
}
for(int k=start;k<=end;k++){
b[k]=tempb[k];
}
return;
}
|