`while(condition){// work}和`do {// work} while(condition)`有什么好处?

Fai*_* S. 0 programming-languages while-loop conditional-statements c#-4.0

我发现自己遇到了一个面试问题,其目标是编写一个排序算法,对一系列未排序的int值进行排序:

int[] unsortedArray = { 9, 6, 3, 1, 5, 8, 4, 2, 7, 0 };
Run Code Online (Sandbox Code Playgroud)

现在我用Google搜索并发现那里有很多排序算法!最后,我可以激励自己深入研究Bubble Sort,因为它看起来很简单.

我阅读了示例代码并找到了一个如下所示的解决方案:

    static int[] BubbleSort(ref int[] array)
    {
        long lastItemLocation = array.Length - 1;
        int temp;
        bool swapped;

        do
        {
            swapped = false;
            for (int itemLocationCounter = 0; itemLocationCounter < lastItemLocation; itemLocationCounter++)
            {
                if (array[itemLocationCounter] > array[itemLocationCounter + 1])
                {
                    temp = array[itemLocationCounter];
                    array[itemLocationCounter] = array[itemLocationCounter + 1];
                    array[itemLocationCounter + 1] = temp;

                    swapped = true;
                }
            }

        } while (swapped);

        return array;
    }
Run Code Online (Sandbox Code Playgroud)

清楚地看到,这是一种情况,do { //work } while(cond)声明是一个很大的帮助,并防止使用另一个辅助变量.

但这是唯一一个更有用的案例,还是您知道使用此条件的任何其他应用程序?

Pet*_*ter 11

一般来说:

  • 使用do...while时要被执行的身体至少一次.
  • 使用while...时,您可能不希望在所有的被执行主体.

编辑:我会说第一个选项约占10%的时间,第二个约占90%.在任何一种情况下,您都可以随时重新考虑使用它们.使用最接近你想说的那个.


Rob*_*vey 5

do... while保证循环内的代码体至少执行一次. 这在某些条件下很方便; 例如,在编码REPL循环时.