I am doing the Algorithm Part I course, and I implemented merge sort using C++. It was supposed to do the in-place sorting but It doesn't sort the array. I am not able to find the reason. Hoping to get a positive response. Thank you.
void merge(int *a, int *aux, int low, int mid, int high) {
for (int k = low; k <= high; ++k)
aux[k] = a[k]; // copy
int i = low, j = mid + 1;
for (int k = low; k <= high; ++k) { // merge
if (i > mid)
a[k] = aux[j++];
else if (j > mid)
a[k] = aux[i++];
else if (aux[i] > aux[j])
a[k] = aux[j++];
else
a[k] = aux[i++];
}
}
void sort(int *a, int *aux, int low, int high) {
if (high <= low)
return;
int mid = low + (high - low) / 2;
sort(a, aux, low, mid);
sort(a, aux, mid + 1, high);
merge(a, aux, low, mid, high);
}
void sort(int *a, int N) {
int *aux = new int[N];
sort(a, aux, 0, N - 1);
}
Your merge function is logically incorrect. For any iteration the last two conditions will never be executed. j
will be always greater than mid
, control will not reach beyond the second expression.
Modify your definition of merge function to something like this:
void merge(int *a, int *aux, int low, int mid, int high) {
for (int k = low; k <= high; ++k)
aux[k] = a[k]; // copy
int i = low, j = mid + 1;
for (int k = low; k <= high; ++k) { // merge
// changes begin here
if (i <= mid and j <= high) {
if (aux[i] > aux[j])
a[k] = aux[j++];
else
a[k] = aux[i++];
}
else if (i > mid)
a[k] = aux[j++];
else // if (j > high)
a[k] = aux[i++];
// changes end here
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.