c++ - qsort 的无限计算

标签 c++ quicksort

根据 Korman 的说法,我正在研究 qsort 算法。但是当我试图启动它时,计算是无限的。我想,那个问题是在分区。我的程序从文件中读取,文件行中的第一个数字是要排序的数字,接下来是所有数字

#include <stdio.h>
#include <stdlib.h>

int swap(int &a, int &b);
int sorting(int *array, int &b, int &l);
int partition(int *array ,int &begin, int &last);


int main()
{
    FILE* pFile=fopen("input.txt", "r");
    //fopen("input.txt", "r");
    //fopen("output.txt", "w");
    int n;
    int begin=0;
    fscanf(pFile, "%d", &n);
    int* array=(int*)malloc(n*sizeof(int));
    for (int i=0; i<n; ++i)
        fscanf(pFile,"%d", &array[i]);
    int n1=n-1;
    sorting(array, begin, n1);
    printf("JJJJ");
    for (int i=0; i<n; ++i)
        printf("%d ", array[i]);
    printf("\n");
    fclose(pFile);
    free(array);
    return 0;
}

int sorting(int* array, int &b, int &l)
{
    int pivot,pivot1;
    if(b<l)
    {
        pivot=partition(array, b, l);
        printf("MAXMAX321");
        int a=pivot-1;
        sorting(array, b, a);
        printf("MAXMAX123");
        pivot1=pivot+1;
        sorting(array, pivot1, l);
        printf("MAXMAX");
    }
    return 0;
}

int partition(int* array, int &b, int &l)
{
    int x=array[b];
    int i=b;
    int j=l;
    while(true)
    {
        while(array[j]>x){
            printf("AHAH");
            --j;
        }
        while(array[i]<x){
            printf("AZAZA");
            ++i;
        }
        if(i<j)
            swap(array[i],array[j]);
        else
            return j; 

    }
}

int swap(int &x, int &y)
{
    x=x+y;
    y=x-y;
    x=x-y;
    return 0;
}

提前谢谢你。

最佳答案

这部分是非常危险的代码:

while(true)
{
    while(array[j]>x){
        printf("AHAH");
        --j;
    }
    while(array[i]<x){
        printf("AZAZA");
        ++i;
    }
    if(i<j)
        swap(array[i],array[j]);
    else
        return j; 

}
  1. 避免while (true)尽可能多地,除非在非常特殊的情况下,你应该在循环中说明一个明确的条件。这是导致“返回”的那个。它将阐明循环的目标。
  2. 当测试像 while(array[i]<x) 这样的数组值时比较 i之前的数组大小!您永远无法确定您的条件是否会始终在数组中得到满足,请确保您系好安全带。

关于c++ - qsort 的无限计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20083018/

相关文章:

c++ - 在 C++ 中获取 `wchar_t*` 的长度

c++ - c++ 标准关于在默认析构函数中丢失抛出说明符的内容

java - 如何在一个数组中打印数组函数?

java - 在 Java 中就地快速排序

c++ - 使用 Quicksort C++ 对数组进行排序

c++ - 如何用二进制流替换字符串流,以避免强制转换?

c++ - 为什么无堆栈协程需要动态分配?

元素少于结构的 C++ 初始值设定项列表

rust - 快速排序算法中 Usize 和 Index 的类型问题

C:尝试实现双枢轴快速排序但陷入无限循环