c++ - What's wrong with my (pointer based) mergesort? -
no errors, doesn't sort list. worked when used indices instead of pointers directly. feel i'm missing way pointer's should behave... . correct in assuming pointers passed value (copied) recursive calls, or messing them down way?
#include<iostream> using namespace std; void merge(int *start, int *pivot, int *end) { const int n = start - end; int ret[n]; int i; (i=0; i<n; ++i) { if (*start < *pivot) { ret[i] = *(start++); } else { ret[i] = *(pivot++); } } (i=0;i<n;++i) { start[i] = ret[i]; } } void sort1(int* start,int* end) { int n = end - start; if (n <= 1) { return; } int* pivot = &start[n/2]; sort1(start,pivot); sort1(pivot,end); merge(start,pivot,end); } int main() { int x[] = {1,3,6,2,4,5}; sort1(x,x+6); int i; (i=0; i<6; ++i) { cout << x[i] << endl; } }
my current output 1 1 3 3 1 1
i think merge @ fault. there no bounds-testing on 2 sub-arrays, reach end of 1 array, you'll taking values other (that have been copied).
it's normal split code merge 3 loops follows:
int *a1 = start; int *a2 = pivot; int *r = &ret[0]; // copy smallest each sub-array while( a1 != pivot && a2 != end ) { if( *a1 < *a2 ) *r++ = *a1++; else *r++ = *a2++; } // copy remaining values first sub-array while( a1 != pivot ) *r++ = *a1++; // copy remaining values second sub-array while( a2 != end ) *r++ = *a2++;
Comments
Post a Comment