我发现自己面临着一个面试问题,其目的是写一个排序算法进行排序无序int
值的数组:while(condition){// work}`和`do {// work} while(condition)`有什么好处?
int[] unsortedArray = { 9, 6, 3, 1, 5, 8, 4, 2, 7, 0 };
现在我用Google搜索,并发现有这么多的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)
语句是一个很大的帮助是,防止使用另一个辅助变量。
但是,这是唯一的情况下,这是更有用的,或者你知道任何其他应用程序,这种情况已被使用?
相关http://stackoverflow.com/questions/1035229/when-is-a-do-while-appropriate/1035234#1035234 – 2010-05-31 18:19:24