简体   繁体   English

使用Quicksort C ++对数组进行排序

[英]Sorting arrays with Quicksort C++

I am working on a projekt (for school) and one of the requirements is to sort an array. 我正在(学校)项目中工作,其中一项要求是对数组进行排序。 So I decided to use the quicksort. 因此,我决定使用quicksort。 (I chose it because it is an algorithm that I don't know by now) I managed to understand how it works and I also found an option of its implementation in c++. (我之所以选择它,是因为它是一种我现在不知道的算法),我设法理解了它的工作原理,并且还找到了在c ++中实现它的选择。

void quicksort(size_t v[], size_t start_pos, size_t end_pos)
{
    size_t i, j, di, dj;
    if (start_pos < end_pos)
    {
        i = start_pos, j = end_pos;
        di = 0, dj = 1;
        do
        {
            while (i < j && (v[j] > v[i] || v[j] == v[i])) i += di, j -= dj;
            if (i < j)
                std::swap(v[i], v[j]), di = (di + 1) % 2, dj = (dj + 1) % 2;
        } while (i < j);
        if (i - start_pos > 1)
            sort(v, start_pos, i - 1);
        if (end_pos - i > 1)
            sort(v, i + 1, end_pos);
    }
}

What I don't understand is... why in the last 2 if statements is used ">1"? 我不明白的是...如果在最后2个语句中使用“> 1”,为什么呢? I hope someone can clarify this for me. 我希望有人可以为我澄清这一点。 Thank you! 谢谢! :) :)

Both calculations provides the size of the left and right subdivision respectively. 两种计算都分别提供了左和右细分的大小。

If the size is 1 or zero, that part is already sorted and doesn't need any further processing. 如果大小为1或零,则说明该部分已经排序,不需要任何进一步的处理。

    if (i - start_pos > 1)  
        sort(v, start_pos, i - 1);  

The sort call is only made if the range is two or more elements. 仅当范围是两个或更多元素时才进行排序调用。 As Barry points out, this should probably be 正如Barry所指出的,这可能应该是

    if (i - start_pos > 1)  
        quicksort(v, start_pos, i - 1);        

Victors comment is also on point. 维克多斯的评论也很重要。

如果仔细看,代码的上半部分将安排与枢轴元素相对应的数组,该元素在i处索引,最后两个if对其余部分(即枢轴元素的左右)进行排序,但是如果您的枢轴索引已经到达end_pos,您不需要在数据透视元素的右边对元素进行排序,因此存在一个条件是否i <end_pos。

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

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