Thursday, 15 April 2010

What am I doing wrong in this C++ mergesort? -



What am I doing wrong in this C++ mergesort? -

the programme compiles , runs properly. list of integers read input file, output displays numbers without changes. expect them sorted to the lowest degree greatest. reference, trying implement version similar illustration on wikipedia.

// arra contains items sort; arrb array work in void mergesort(int *arra, int *arrb, int first, int last) { // 1 element array sorted // create increasingly longer sorted lists (int width = 1; width < last; width = 2 * width) { // arra made of 1 or more sorted lists of size width (int = 0; < last; += 2 * width) { // merge 2 sorted lists // or re-create arra arrb if arra total merge(arra, i, min(i+width, last), min (i + 2 * width, last), arrb); } // end // arrb total of sorted lists of size 2* width // re-create arrb arra next iteration copy(arrb, arra, last); } // end } // end mergesort void merge(int *arra, int ileft, int iright, int iend, int *arrb) { int i0 = ileft, i1 = iright; // while either list contains integers (int j = ileft; j < iend; j++) { // if 1st integer in left list <= 1st integer of right list if (i0 < iright && (i1 >= iend || arra[i0] <= arra[i1])) { arrb[j] = arra[i0]; i0 += 1; } // end if else { // right head > left head arrb[j] = arra[i0]; i0 += 1; } // end else } // end } // end merge void copy(int *origin, int *destination, int size) { (int = 0; < size; i++) { destination[i] = origin[i]; } // end } // end re-create int main() { int size = 0, first = 0, *arra, *arrb; // input info read(&arra, &arrb, &size); // sorting mergesort(arra, arrb, first, size); // output write(arra, first, size); // cleanup delete [] arra; delete [] arrb; } input 33 9 -2 output 33 9 -2

i haven't looked @ code, if-statement seems bit off me:

if (i0 < iright && (i1 >= iend || arra[i0] <= arra[i1])) { arrb[j] = arra[i0]; i0 += 1; } // end if else { // right head > left head arrb[j] = arra[i0]; i0 += 1; } // end else

surely, whole point of pair of if/else clauses different things in if vs. else part. far can tell, it's identical here.

c++ mergesort

No comments:

Post a Comment