c - Can't spot the error in Mergesort -


l & h corresponds indices of 1st & last elements in array a:- individual partition , merging functions working well. please explain error occurring in linking of 2 functions.

#include <stdio.h> void mergesort(int a[], int l, int h); void merge (int a[], int l, int m, int h); int main () {     int a[] = {5,4,9,0,8,6,1,3,2,7}, i;     mergesort (a, 0, 5);     (i = 0; < 10; i++)         printf ("%d ", a[i]);     return 0; } void mergesort(int a[], int l, int h)  {     if (l == h)     return;     int m = (l + h) / 2;     mergesort (a, l, m);     mergesort (a, m + 1, h);     merge(a, l, m, h); } void merge (int a[], int l, int m, int h) {     int t[h - l + 1], = l, j = m + 1, k = 0;     while (i <= m && j <= h) {         if (a[i] < a[j]){             t[k] = a[i];             k++;             i++;         }         if (a[j] < a[i]) {             t[k] = a[j];             j++;             k++;         }     }     if (i != m) {         while (i <= m) {             t[k] = a[i];             k++;             i++;         }     }     if (j != h) {         while (j <= h) {             t[k] = a[j];             k++;             j++;         }     }     (i = 0; <= (h - l); i++)         a[l + i] = t[i];     } 

instead of desired output

0 4 5 6 8 9 1 3 2 7 

(the elements 0 5 inclusive become sorted), produces garbage like

0 4 6 9 2686712 32 1 3 2 7 

the lines if (i != m) , if (j != h) must if (i <= m) , if (j <= h).

besides, can omit them because redundant (leave while conditions). less code, less bugs.


Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -