This is for my computer science c++ data structures class.
For my assignment I have to create mergesort code for ascending and descending arrays.
My professor has me compile his test code along with my file code. The terminal will print out any errors in my coding logic.
This is the error that prints out in the terminal when I run my file:
**** Testing mergesort **** Testing simple two-element merge: OK Testing 20-element merge (10 and 10): OK Testing 21-element merge: OK Sorting empty sequence:OK Sorting random vector of size 2: {48, 77} OK Sorting random vector of size 3: {48, 77, 64} OK Sorting random vector of size 4: {48, 77, 64, 2} OK Sorting random vector of size 5: {48, 77, 64, 2, 11} FAILED: result is not sorted: {11, 2, 48, 64, 77}
This is my code:
void merge(int *input, int size, int *output, bool output_asc) {
if (output_asc == true) { //sort ascending
int i = 0;
int j = size - 1;
int k = 0;
while (i <= j) {
if (input[i] <= input[j]) {
output[k++] = input[i++];
} else {
output[k++] = input[j--];
}
}
} else
if (output_asc == false) { //sort descending
int i = 0;
int j = size - 1;
int k = 0;
while (i <= j) {
if (input[i] <= input[j]) {
output[k++] = input[j--];
} else {
output[k++] = input[i++];
}
}
}
}
void mergesort(int *input, int size, int *output, bool output_asc) {
int begin = 0;
int end = size - 1;
if (begin >= end) {
return;
}
int mid = (begin + end) / 2;
mergesort(input, mid - 1, output, output_asc);
mergesort(input, end, output, output_asc);
merge(input, size, output, output_asc);
}
int *mergesort(int *input, int size) {
int *output = new int[size];
mergesort(input, size, output, true);
return output;
}
This is my professors test code:
/* test_mergesort()
Test mergesort on a variety of inputs.
*/
bool test_mergesort() {
cout << "Sorting empty sequence:";
vector<int> no_data;
int *no_data_sorted = mergesort(no_data);
// No data means nothing to check!
delete[] no_data_sorted;
cout << "OK\n";
vector<int> sizes = { 2, 3, 4, 5, 7, 8, 15, 16, 19, 20, 50, 64, 100, 128 };
for (int s : sizes) {
// Test sorting a vector of random data
vector<int> data = make_random_vector(s);
cout << "Sorting random vector of size " << s << ":\n" << data << "\n";
int *data_sorted = mergesort(data);
if (!is_sorted(data_sorted, data.size())) {
cout << "FAILED: result is not sorted:\n";
cout << "{";
for (int *i = data_sorted; i != data_sorted + data.size() - 1; ++i)
cout << *i << ", ";
cout << data_sorted[data.size() - 1] << "}\n";
return false;
} else
if (!is_permutation(&data[0], data.size(), data_sorted)) {
cout << "FAILED: result is not a permutation of the input sequence:\n";
cout << "{";
for (int *i = data_sorted; i != data_sorted + data.size() - 1; ++i)
cout << *i << ", ";
cout << data_sorted[data.size() - 1] << "}\n";
return false;
} else
cout << "OK\n";
}
return true;
}
Any help will be appreciated, thank you.