c++ - Merge sort not working completely -
the code have made merge sort given below. thing on giving input output 3 2 1 5 0. going wrong?
#include <iostream> #include <cmath> using namespace std; int d[100]; void merge(int a[], int b[], int c[], int n) { int n2=floor(n/2); int i=0, j=0, k=0; while(i<n2 && j<(n-n2)) { if(b[i]<c[j]) { d[k++]=b[i++]; } else if(b[i]>c[j]) { d[k++]=c[j++]; } } if(i==n2) { if(j<(n-n2)) { d[k++]=c[j++]; } } if(i<n2) { d[k++]=b[i++]; } } void mergesort(int a[], int n) { int n2=floor(n/2); int b[50],c[50]; int i,j=0,k=0; for(i=0;i<n2;i++) { b[i]=a[k++]; } while(k<n) { c[j++]=a[k++]; } merge(a,b,c,n); } int main() { int a[]={5,4,3,2,1}; int n=5; mergesort(a,n); for(int i=0;i<n;i++) { cout<<d[i]<<endl; } }
the main problem arrays (b , c) passed merge not sorted. other problems algorithm not recursive , merge not put numbers b , c a.
a version seems work minimal changes code be
void merge(int a[], int b[], int c[], int n) { int n2=floor(n/2); int i=0, j=0, k=0; while(k<n) { if((j == (n-n2) || b[i]<c[j]) && < n2) { a[k++]=b[i++]; } else { a[k++]=c[j++]; } } } void mergesort(int a[], int n) { int n2=floor(n/2); int b[50],c[50]; int i,j=0,k=0; for(i=0;i<n2;i++) { b[i]=a[k++]; } while(k<n) { c[j++]=a[k++]; } if(n2 > 1) { mergesort(b, n2); } if(n - n2 > 1) { mergesort(c, n - n2); } merge(a,b,c,n); } int main() { int a[]={5,4,3,2,1}; int n=5; mergesort(a,n); for(int i=0;i<n;i++) { cout<<a[i]<<endl; } }
Comments
Post a Comment