Mergesort implementation in C -
can please check mergesort code. when tried sorting input values, sorted array contained random values weren't input. , not sorted. way i'm declaring array within while loop correct?
#include <stdio.h> void merge (int a[], int aux[], int lo, int mid, int hi){ for(int y=lo; y<=hi; y++){ aux[y]=a[y]; } int i=lo; int j=mid+1; for(int k=lo;k<=mid;k++){ if (j>hi) a[k]=aux[i++]; else if (i>mid) a[k]=aux[j++]; else if (a[j]<a[i]) a[k]= aux[j++]; else a[k]=aux[i++]; } return; } void sort (int b[],int aux[], int lo, int hi) { if(hi<=lo) return; int mid= lo+(hi-lo)/2; sort(b, aux, mid+1, hi); sort(b, aux, lo, mid); merge(b,aux,lo,mid,hi); return; } int main(void) { int t,n; long long int sum; scanf("%d",&t); while(t--){ sum=0; scanf("%d",&n); int w[n]; int m[n]; int g[n]; int h[n]; (int i=0; i<n;i++){ scanf("%d",&m[i]); } (int j=0; j<n;j++){ scanf("%d",&w[j]); } sort(w,g,0,n-1); sort(m,h,0,n-1); } return 0; }
you compareing meaningless values in merge
funtion , stop merging in middle of processs.
to correct them, in merge
function
- change
k<=mid
k<=hi
- change
a[j]<a[i]
aux[j]<aux[i]
Comments
Post a Comment