【发布时间】:2010-05-31 18:12:54
【问题描述】:
我发现自己面临一个面试问题,目标是编写一个排序算法,对一组未排序的int 值进行排序:
int[] unsortedArray = { 9, 6, 3, 1, 5, 8, 4, 2, 7, 0 };
现在我搜索了一下,发现外面有这么多sorting algorithms! 最后我可以激励自己深入研究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;
}
我清楚地看到这种情况,do { //work } while(cond) 语句很有帮助,并且可以防止使用另一个辅助变量。
但这是唯一更有用的情况吗?或者您知道使用此条件的任何其他应用程序吗?
【问题讨论】:
标签: programming-languages c#-4.0 while-loop conditional-statements