【问题标题】:Can anyone help me find what is wrong with my code?谁能帮我找出我的代码有什么问题?
【发布时间】:2021-07-31 06:20:48
【问题描述】:

我用 C++ 编写了快速排序代码,但它不起作用。谁能告诉我这段代码有什么问题?每当我提供输入时,它都不会返回任何输出。 示例:

5

5 4 3 6 2


进程在 5.997 秒后退出,返回值 3221225725 按任意键继续 。 . .

为什么它没有返回任何输出?即使我检查了很多次代码,但我仍然面临同样的问题

#include<iostream>

using namespace std;

void swap(int *a, int *b)           //swap function 

{

    int c;

    c=*b;

    *b=*a;

    *a=c;

}

int partition(int arr[], int i, int j)             //partition function

 {

    int pivot=arr[j];
    while(i<j) {
        while(i<=pivot) {
            i++;
        }
        while(j>=pivot) {
            j--;
        }
        if(i<j) {
            swap(&arr[i],&arr[j]);
        }
    }
    swap(&pivot,&arr[j]);
    return j;
}

void quicksort(int arr[], int i, int j)   //quicksort function

 {

    if(i<j) {
        int p;
        p=partition(arr,i,j);
        quicksort(arr,i,p-1);
        quicksort(arr,p+1,j);
    }
}

    void print(int arr[],int n)      //function to print the array
    
     {
    
    for(int i=0;i<n;i++) {
    cout<<arr[i]<<" ";
    }
    
    }

int main() 

{

    int n;
    cin>>n;
    int arr[n];
    for(int i=0;i<n;i++) {
        cin>>arr[i];
    }
    int x=0,y=n-1;
    quicksort(arr,x,y);
    print(arr,n);
    return 0;
}

【问题讨论】:

  • StackOverflow 不是调试服务。到目前为止,您尝试过什么来尝试自己解决此问题?您是否使用实际的调试器单步执行了代码? “它不起作用”不是对问题的有效描述。究竟是什么不工作?给出了什么输入?预期输出是多少,实际输出是多少?具体一点。
  • 每次我插入一个输入,它不会给出任何输出。它只是说- Process exited after 5.997 seconds with return value 3221225725 Press any key to continue 。 . .
  • 禁用快速排序功能,先取输入打印出来,看输入是否正确
  • 我已经尝试过了,它可以正确输入。 @sittsering
  • 启用警告后,您的编译器对int arr[n]; 有什么看法?

标签: c++ arrays data-structures quicksort


【解决方案1】:

它应该是 while(arr[i]&lt;=pivot) 而不是 while(i&lt;=pivot) j 也是如此

int partition(int arr[], int i, int j) 

 {

    int pivot=arr[j];
    while(i<j) {
        while(arr[i]<=pivot) {
            i++;
        }
        while(arr[j]>pivot) {
            j--;
        }
        if(i<j) {
            swap(&arr[i],&arr[j]);
        }
    }
    swap(&pivot,&arr[j]);
    return j;
}

【讨论】:

  • 谢谢@sittsering。它有帮助。另外,我将while(arr[j]&gt;=pivot) 更改为while(arr[j]&gt;pivot),它成功了。
猜你喜欢
  • 2021-10-05
  • 2011-08-15
  • 1970-01-01
  • 2021-07-14
  • 2020-04-29
  • 1970-01-01
  • 2021-10-18
  • 1970-01-01
  • 2015-05-17
相关资源
最近更新 更多