c++ - Merge sort make wrong answer -
i trying implement merge-sort, code:
#include <stdio.h> #include <stdlib.h> #include <iostream> #include <fstream> using namespace std; void merge_inplace (int *elem , int *axu, int lo, int mid, int hi) { int =lo; int j= mid +1; (int k=lo;k<hi; k++) { axu[k]=elem[k]; } for(int k=lo; k<hi;k++) { if(i> mid) elem[k]=axu[i++]; else if(j> hi) elem[k]=axu[j++]; else if (axu[i]<axu[j]) elem[k]= axu[i++]; else elem[k]= axu[j++]; } } void mergesort(int *elem ,int *axu, int lo,int hi) { if(hi<=lo) return; int mid = lo + (hi-lo)/2; mergesort(elem,axu, lo, mid); mergesort(elem,axu, mid+1,hi); merge_inplace(elem,axu,lo, mid, hi ); } int main() { ifstream in_file ; ofstream out_file; int size =0; int element; int* elem; in_file.open("in_file.txt"); if (!in_file )perror ("error openning file"); in_file >> size; elem = new int[size]; (int i=0; i<size;i++) { in_file >> elem[i]; } int * axu = new int [size]; mergesort (elem,axu,0,size-1); out_file.open("out_file.txt"); if (out_file.fail()) { printf( "error opening file output.\n"); return 0; } (int i=0; < size; i++) { out_file << elem[i]; } out_file.close(); return 0; }
the out put of program in "out_file.txt "is :
-842150451-842150451-842150451-842150451-842150451-842150451-33686019-1414812757-84215045110
after debugging found when merge function returns element array destroy , make values wrong
my input file contain (one integer per line ):
10 9 7 5 1 8 3 6 4 2 10
some mistake on merge-sort & transferring aux initialization merge sort function
#include <stdio.h> #include <stdlib.h> #include <iostream> #include <fstream> using namespace std; void merge_inplace (int *elem , int *axu, int lo, int mid, int hi) { int =lo; int j= mid +1; (int k=0;k<=hi; k++) // <------------- transfer initialization merge { axu[k]=elem[k]; } for(int k=lo; k<=hi;k++) { if(i> mid) elem[k]=axu[j++]; // <----------------- i<--->j else if(j> hi) elem[k]=axu[i++]; // <------------------ i<--->j else if (axu[i]<axu[j]) elem[k]= axu[i++]; else elem[k]= axu[j++]; } } void mergesort_book(int *elem ,int *axu, int lo,int hi) { if(hi<=lo) return; int mid = lo + (hi-lo)/2; mergesort_book(elem,axu, lo, mid); mergesort_book(elem,axu, mid+1,hi); merge_inplace(elem,axu,lo, mid, hi ); } //static void merge(vector <int> elements, ) int main() { ifstream in_file ; ofstream out_file; int size =0; int element; int* elem; in_file.open("in_file.txt"); if (!in_file )perror ("error openning file"); in_file >> size; elem = new int[size]; (int i=0; i<size;i++) { in_file >> elem[i]; } int * axu = new int [size]; mergesort_book (elem,axu,0,size-1); out_file.open("out_file.txt"); if (out_file.fail()) { printf( "error opening file output.\n"); return 0; } (int i=0 ; < size; i++) { //out_file << elem[i]; printf("%d\n", elem[i]); } out_file.close(); return 0; }
Comments
Post a Comment