0

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!

2
  • Maybe it is too quick, is not it? :) Commented Jul 7, 2015 at 20:25
  • st=v[1]; dr=v[n]; should be st=0; dr=n-1;, if I'm not mistaken? What do you think it does? Commented Jul 7, 2015 at 20:30

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.