简体   繁体   中英

QuickSort not sorting array

I've been trying to make a qsort algorithm, but so far I've failed miserably. Keep in mind I'm kind of a newbie when it comes to programming, so yeah. After I build and run, and input my array, it returns the same exact array, instead of sorting it. Here's the code in question:

 #include <iostream>

using namespace std;

int v[11], i, n, st, dr;

void qsort (int v[11], int st, int dr)
{
    int i=st, j=dr;
    int aux;
    int pivot = v[(st+dr)/2];
    while(i<=j)
        while(v[i]<pivot)
        {
            i++;
            if(i<=j)
            {
                aux=v[i];
                v[i]=v[j];
                v[j]=aux;
                i++;
                j--;
            }
        }
    if(st<j)
        qsort(v,st,j);
    if(i<dr)
        qsort(v,i,dr);

}


int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
        cin>>v[i];
    st=v[1];
    dr=v[n];
    qsort(v, st, dr);
    cout<<"vectorul sortat este"<<' ';
    for(i=1;i<=n;i++)
        cout<<v[i]<<' ';
    return 0;
}

Thanks in advance!

st and dr should be the initial and final indices where you want to sort, not the values (also, keep in mind that in C++ a vector on n elements has indices from 0 to n-1, so fix also your for loops), so you have to change

st=v[1];
dr=v[n];

to

st=0
dr=n-1

or simply:

qsort(v, 0, n-1);

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