#include<stdio.h> #include<stdlib.h> int main() { int n,a[1000]; scanf_s("%d", &n); for (int m = 0; m < n; m++) { scanf_s("%d", &a[m]); } mergesort(a, 0, n); for (int m = 0; m < n; m++) { printf("%d", a[m]); } return 0; } void merge(int *a, int low, int mid, int high) { int i, j, k = low; int b[1000] = { 0 }; i = low; j = mid + 1; while (i <= mid && j <= high) { if (a[i] <= a[j]) { b[k] = a[i++]; } else b[k] = a[j++]; k++; } while (i <= mid) b[k++] = a[i++]; while (j <= high) b[k++] = a[j++]; for (k = low; k <= high; k++) { a[k] = b[k]; } } void mergesort(int *a, int low, int high) { int mid = (low + high) / 2; if (low < high) { mergesort(a, low, mid); mergesort(a, mid + 1, high); merge(a, low, mid, high); } }修改错误
时间: 2024-01-18 16:04:06 浏览: 125
在程序中发现一个错误,`mergesort(a, 0, n)`应该改为`mergesort(a, 0, n-1)`,因为数组下标是从0开始的。修改后的代码如下:
```c
#include<stdio.h>
#include<stdlib.h>
void merge(int *a, int low, int mid, int high) {
int i, j, k = low;
int b[1000] = { 0 };
i = low;
j = mid + 1;
while (i <= mid && j <= high) {
if (a[i] <= a[j]) {
b[k] = a[i++];
} else {
b[k] = a[j++];
}
k++;
}
while (i <= mid) {
b[k++] = a[i++];
}
while (j <= high) {
b[k++] = a[j++];
}
for (k = low; k <= high; k++) {
a[k] = b[k];
}
}
void mergesort(int *a, int low, int high) {
int mid = (low + high) / 2;
if (low < high) {
mergesort(a, low, mid);
mergesort(a, mid + 1, high);
merge(a, low, mid, high);
}
}
int main() {
int n,a[1000];
scanf_s("%d", &n);
for (int m = 0; m < n; m++) {
scanf_s("%d", &a[m]);
}
mergesort(a, 0, n-1);
for (int m = 0; m < n; m++) {
printf("%d ", a[m]);
}
return 0;
}
```
阅读全文