当我运行 QuickSort 代码并输入数字时。 根本没有任何输出。 我不知道问题所在。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
void quickSort(int *pA, int left, int right) {
int i, j, t, temp;
temp = pA[left];
i = left;
j = right;
while (i != j) {
while (i < j && pA[j] >= temp)
j--;
while (i < j && pA[i] <= temp)
i++;
if (i < j) {
t = pA[i];
pA[i] = pA[j];
pA[j] = t;
}
}
pA[left] = pA[i];
pA[i] = temp;
quickSort(pA, left, i - 1);
quickSort(pA, i + 1, right);
}
int main() {
int i, n, a[100];
printf("please input the total of numbers:");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("number %d is:", i + 1);
scanf("%d", &a[i]);
}
quickSort(&a, 0, n - 1);
for (i = 0; i < n; i++) {
printf("%d ", a[i]);
}
return 0;
}
最佳答案
您必须在递归 quickSort
中添加测试才能停止递归!例如,只有 1 个条目的段显然已排序。
这是更正后的版本:
#include <stdio.h>
void quickSort(int *pA, int left, int right) {
int i, j, t, temp;
if (right - left < 1)
return;
temp = pA[left];
i = left;
j = right;
while (i != j) {
while (i < j && pA[j] >= temp)
j--;
while (i < j && pA[i] <= temp)
i++;
if (i < j) {
t = pA[i];
pA[i] = pA[j];
pA[j] = t;
}
}
pA[left] = pA[i];
pA[i] = temp;
quickSort(pA, left, i - 1);
quickSort(pA, i + 1, right);
}
int main(void) {
int i, n, a[100];
printf("please input the total of numbers: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("number %d is: ", i + 1);
scanf("%d", &a[i]);
}
quickSort(a, 0, n - 1);
for (i = 0; i < n; i++) {
printf("%d ", a[i]);
}
printf("\n");
return 0;
}
关于c - [QuickSort]递归问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35014344/