简体   繁体   中英

Bug in quick sort function in C

#include<iostream>
using namespace std;
int swap(int *a,int i,int j)
{
    int temp=a[i];
    a[i]=a[j];
    a[j]=temp;
}
int pivot(int *a,int low,int high)
{
    int j,i=low-1,x=a[high];
    for(j=i+1;j<high;j++)
    {
        if(a[j]<x)
            swap(a,j,++i);
    }
    swap(a,i,high);
    return i;
}
int quick(int *a, int low, int high)
{
    if(low<high)
    {
        int p=pivot(a,low,high);
        quick(a,low,p-1);
        quick(a,p+1,high);
    }
}
int main()
{
    int a[]={3,2,1,5,8,7,5,6,9,8},i;
    quick(a,0,9);
    for(i=0;i<10;i++)
        cout<<a[i]<<" ";
    return 0;
}

Can you please help me figure out why this code is not giving output. I tried my level best to figure out but I am not getting where is the bug. In my opinion there is some small mistake in the code.

Use this in your pivot function before return statement.

swap(a,++i,high);

instead of

swap(a,i,high);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM