简体   繁体   English

C#while循环未退出(快速排序)

[英]C# while loop not exiting (quicksort)

for some reason, my while loop for (i<=j) does not end when j goes lower than i. 由于某些原因,当j小于i时,我的(i <= j)的while循环不会结束。

I watched the debug values, and have repeatedly seen values of (4,3), (6,5) etc for i and j (respectively). 我观看了调试值,并分别反复看到了i和j的(4,3),(6,5)等值。

public static List<Item> QuickSort(List<Item> a, int left, int right)
{
    int i = left;
    int j = right;
    double pivotValue = ((left + right) / 2);
    Item x = a[Convert.ToInt32(pivotValue)];
    Item w;
    while (i <= j)
    {
        //these while loops continue looping after i<=j is false
        while (a[i] < x)
        {
            i++;
        }
        while (x < a[j])
        {
            j--;
        }
        if (i <= j)
        {
            w = a[i];
            a[i++] = a[j];
            a[j--] = w;
        }
    }
    if (left < j)
    {
        QuickSort(a, left, j);
    }
    if (i < right)
    {
        QuickSort(a, i, right);
    }
    return a;
}

I'll bet it's either the recursion or one of the internal while loops that's still going on. 我敢打赌,仍然是递归还是内部while循环之一。 I don't have the quicksort algorithm memorized, but I'd wager that if you broke in the debugger you'd find yourself in one of the two inner while loops. 我没有记住quicksort算法,但是我敢打赌,如果您闯入了调试器,您将发现自己处于两个内部while循环之一。

Coding quicksort is a very good exercice, it's not as easy as it may look to get everything right! 编码快速排序是一个很好的练习,它并不容易使一切正确! ;) ;)

Here's one problem with your code. 这是您的代码的一个问题。 Consider what happens if j bumps into the pivot, while i does not. 考虑一下,如果j碰到枢轴,而i没有,会发生什么。 You exchange the pivot (at j ) with the value at i and increment i past the pivot. 您将枢轴(在j )与i上的值交换,并使i越过枢轴。 This cannot continue correctly (if you understand Quicksort you should understand why). 这不能正确继续(如果您了解Quicksort,则应了解原因)。

After choosing the pivot, I like to exchange it with one bound (either left or right ), go exchange values until i and j meet and then put the pivot back at this place. 选择枢轴后,我希望将其与一个边界( leftright )进行交换,交换值直到ij相遇,然后将枢轴放回此位置。 There are other ways, of course. 当然,还有其他方法。

It is not a infinite loop. 这不是一个无限循环。

while (a[i] < x)
    {
        i++;
    }

If x is the largest number in the list, it will raise 'i' as long as the array is out of Range, and the programm will throw a OutOfRangeException. 如果x是列表中最大的数字,则只要数组超出范围,它就会加'i',并且程序将抛出OutOfRangeException。

What happens if i==j and a[i]==x ...? 如果i==j a[i]==x ...会发生什么? No increment, no decrement, just swap and continue... 没有增量,没有减量,只需交换并继续...

Consider changing while(i<=j) to while(i<j) . 考虑将while(i<=j)更改为while(i<j) Also swap is not necessary if i==j ... 如果i==j ...

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

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