简体   繁体   English

QuickSort不对数组进行排序

[英]QuickSort not sorting array

I've been trying to make a qsort algorithm, but so far I've failed miserably. 我一直在尝试制作qsort算法,但到目前为止,我失败了。 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 stdr应该是要排序的初始索引和最终索引 ,而不是 (还要记住,在C ++中,n个元素上的向量的索引从0到n-1,因此还要修复for循环),所以你必须改变

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

to

st=0
dr=n-1

or simply: 或者简单地:

qsort(v, 0, n-1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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