Reputation: 111
The program compiles and runs properly. A list of integers is read from an input file, but the output displays those numbers without any changes. I expect them to be sorted from least to greatest. For reference, I am trying to implement a version similar to the example on wikipedia.
// arrA contains items to sort; arrB is an array to work in
void mergesort(int *arrA, int *arrB, int first, int last) {
// a 1 element array is already sorted
// make increasingly longer sorted lists
for (int width = 1; width < last; width = 2 * width) {
// arrA is made up of 1 or more sorted lists of size width
for (int i = 0; i < last; i += 2 * width) {
// merge two sorted lists
// or copy arrA to arrB if arrA is full
merge(arrA, i, min(i+width, last), min (i + 2 * width,
last), arrB);
} // end for
// now arrB is full of sorted lists of size 2* width
// copy arrB into arrA for next iteration
copy(arrB, arrA, last);
} // end for
} // end mergesort
void merge(int *arrA, int iLeft, int iRight, int iEnd, int *arrB) {
int i0 = iLeft, i1 = iRight;
// while either list contains integers
for (int j = iLeft; j < iEnd; j++) {
// if 1st integer in left list is <= 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 for
} // end merge
void copy(int *origin, int *destination, int size) {
for (int i = 0; i < size; i++) {
destination[i] = origin[i];
} // end for
} // end copy
int main() {
int size = 0, first = 0, *arrA, *arrB;
// input data
read(&arrA, &arrB, &size);
// sorting
mergesort(arrA, arrB, first, size);
// output
write(arrA, first, size);
// cleanup
delete [] arrA;
delete [] arrB;
}
33 9 -2
33 9 -2
Upvotes: 0
Views: 118
Reputation: 129314
I haven't looked very deeply at your code, but this if-statement seems a bit off to 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, the whole point of a pair of if/else clauses is that you do different things in the if vs. the else part. As far as I can tell, it's identical here.
Upvotes: 5