简体   繁体   English

为它排序 - 快速排序

[英]Sorting for the heck of it — Quicksort

We have to make an optimized quicksort for out own Comparable base class. 我们必须为自己的Comparable基类制作一个优化的快速排序。 For the life of me I cannot make it work. 对于我的生活,我无法使它成功。 The algorithm seems straight forward, however I cannot seen to get my code to work. 该算法似乎很简单,但我无法看到让我的代码工作。 I have a DateTime class that extends Comparable that I am using to test and the sort seems to work but one out of every 20 or so runs a single value is out of place and when I use insertion sort on chunks of the array that are less than 8 the whole sort gets thrown out of whack. 我有一个DateTime类,它扩展了我用来测试的Comparable,并且排序似乎有效,但是每20个左右一个运行单个值是不合适的,当我在数组的块上使用插入排序时超过8,整个类型被抛出了重击。

In my partition method it kind of works when I move the pivot to the end and start my pointers at the start and end - 1. I want to move the pivot to end - 1 because the first and last are already sorted and start the pointers at first + 1 and end -2 but everything falls apart if I try that and I don't understand why. 在我的分区方法中,当我将枢轴移动到结束并在开始和结束时启动我的指针时,它有用 - 1.我想将枢轴移动到结束 - 1因为第一个和最后一个已经排序并启动指针在第一个+ 1和结束-2但是如果我尝试这一切并且我不明白为什么,一切都会崩溃。

So I have something that works now. 所以我现在有一些功能。 It gets a little spastic when I don't use insertion sort on smaller sub arrays which bothers be but ill figure it out eventually. 当我不在较小的子阵列上使用插入排序时,它会有点痉挛,这些阵列很困难,但最终会弄清楚。 Thanks to ben j for pointing out about falling out of the array...that was causing the insertion sort issue. 感谢ben j指出有关数组掉线的问题......这导致了插入排序问题。 :) :)

My current code is below 我目前的代码如下

    Comparable** partition(Comparable** from, Comparable** to)
{
    Comparable** pivot  = from + (to - from) / 2;
    SortFirstMiddleLast(from, pivot, to - 1);
    swap(*pivot, *to);
    pivot = to;
    ++from; to -= 2;
    while (from <= to)
    {
        while (**from <= **pivot && from <= to) ++from;
        while (**to   >= **pivot && from <= to) --to;
        if (from < to)
        {
            swap(*from, *to);
            ++from; --to;
        }
    }
    swap(*from, *pivot);
    return from;
}

From the code you've shown us and your comment about what goes wrong my only guess is that from and to do not mean what you think. 从你告诉我们,你的什么去评论的代码错误我唯一的猜测是, fromto并不意味着你的想法。 Your code has to - from as the length of the segment to sort. 您的代码必须to - from作为要排序的段的长度。 If that's exact (and not just approximate for pivot selection) that would mean that to was actually pointing at an element just beyond the region to sort. 如果这是确切的(而不是为支点的选择只是近似值),这将意味着, to在一个元素实际上是指向刚刚超越区域进行排序。 That's reasonable, but then swap<Comparable*>(*pivot, *(to)) would be swapping the pivot off the end of the list. 这是合理的,但是然后swap<Comparable*>(*pivot, *(to))会将数据库交换到列表末尾。

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

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