c - [QuickSort]递归问题

标签 c algorithm

当我运行 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;
}

接下来是代码运行图: enter image description here

最佳答案

您必须在递归 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/

相关文章:

c - 不允许函数定义/

c - 在 C 中实现互斥锁

c++ - 使用 BGL 创建生成树

algorithm - 蒙特卡洛树搜索,反向传播(备份)步骤 : Why change perspective of reward value?

algorithm - 我可以使用哪种井字游戏算法来确定 AI 的 "best move"?

c - umount 不适用于 C 中的设备(但可以在终端中使用)

c - 为什么 C 中的指针减法会产生一个整数?

algorithm - 当给定数字组时,如何找到代表所有数字的最小组集?

algorithm - 程序中的模数优化

c - c中串口读取,使用WinApi函数; WaitCommEvent 失败