c++ - What is wrong with this merge sort algorithm? Stuck since past hour -


#include<iostream> using namespace std;  void storedata(int array[]); void partition(int array[], int, int); void displaydata(int[]); void merge(int[], int,int,int);  int main() {     int array[5];     storedata(array);     partition(array, 5-1,0);     displaydata(array); }  void storedata(int array[]) {      for(int i=0;i<5;i++)     {         cout << "\nenter "<<i+1<< "th element: ";         cin >> array[i];     } }  void displaydata(int array[]) {     cout << "the sorted array is:" << endl;     for(int i;i<5;i++)         cout << array[i] << endl; }  void partition(int array[], int high, int low) {     int mid;     if(low<high)     {         mid = (low+high)/2;         partition(array, mid, low);         partition(array, high, mid+1);         merge(array, high, mid, low);     } }  void merge(int array[], int high, int mid, int low) {     int temp[20];     int h=high, l=low, m=mid+1, k=0;      while(l<=mid && m<=high)     {         if(array[l]>array[m])         {             temp[k]= array[l];             k++;             l++;         }         if(array[m]>array[l])         {             temp[k]= array[m];             k++;             m++;         }     }      if(m<high)     {         while(m<=high)         {             temp[k]=array[m];             m++;             k++;         }     }      else     {         while(l<=mid)         {             temp[k]=array[l];             l++;             k++;         }     }      for(int i=low;i<=high;i++)     {         array[i] = temp[i];     } } 

this piece of code giving out garbage values output when asked sorted array. have tried different options , changed code many times still no go! can please give me little advice on how encounter such problems in future? prove helpful!

in end of merge, loop copy temp array not correctly indexed:

for(int i=low;i<=high;i++) {     array[i] = temp[i]; } 

change to:

for(int = low, j = 0; <= high; i++, j++) {     array[i] = temp[j]; } 

Comments