Programming languages “while(condition){//work}”和“do{//work}while(condition)`有什么好处?
我发现自己面临一个面试问题,目标是编写一个排序算法,对未排序的int值数组进行排序: 现在我在谷歌上搜索,发现外面有那么多人! 最后,我可以激励自己去深入研究,因为这看起来很简单 我阅读了示例代码,得出了如下解决方案:Programming languages “while(condition){//work}”和“do{//work}while(condition)`有什么好处?,programming-languages,c#-4.0,while-loop,conditional-statements,Programming Languages,C# 4.0,While Loop,Conditional Statements,我发现自己面临一个面试问题,目标是编写一个排序算法,对未排序的int值数组进行排序: 现在我在谷歌上搜索,发现外面有那么多人! 最后,我可以激励自己去深入研究,因为这看起来很简单 我阅读了示例代码,得出了如下解决方案: static int[] BubbleSort(ref int[] array) { long lastItemLocation = array.Length - 1; int temp; bool swapped;
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}whilecond语句是一个很好的帮助,可以防止使用另一个helper变量
但是,这是唯一一种更有用的情况,还是您知道使用此条件的任何其他应用程序?do…同时保证循环中的代码体至少执行一次。在某些条件下,这可能很方便;例如,在对REPL循环进行编码时。通常:
如果希望主体至少执行一次,请使用do…while。
使用时。。。当您可能根本不希望执行主体时。
编辑:我认为第一个选项出现的时间约为10%,第二个选项出现的时间约为90%。在任何一种情况下,您都可以重新考虑使用其中一种。使用最接近你想说的话。任何时候你需要循环一些代码直到满足某个条件,这是何时使用do…while或while 一个关于何时使用do…while或while。。。如果您有一个游戏或模拟,其中游戏引擎持续运行各种组件,直到出现赢或输的情况
当然,这只是一个例子。以上关于两种条件循环形式的帖子是正确的。有些语言有repeat-till形式,而不是do-while形式。还有一种极简主义的观点,认为语言中只应该存在必要的控制结构。whiledo是必要的,但do while不是。至于冒泡排序,你要避免去那里,因为它是最慢的常见排序算法。请查看选择排序或插入排序。快速排序和合并排序速度很快,但是如果不使用递归就很难编写,而且如果您碰巧选择了一个糟糕的pivot值,则执行效果会很差。相关的REPL循环?你指的是读取-评估-打印循环吗?@Shaharyar:如果你是在编写一个REPL循环,而不是使用它。这只是一个非常简单的例子。@RobertHarvey-他的意思是mock:REPL Loop==Read Eval Print Loop这就是我使用其中一个的原因。您提供了一个例子,但是你没有说明哪种while模式适合你的例子。@Robert基于when are do while and while do help的问题,让我相信OP想要的是何时使用其中一种模式的例子,而不是何时使用其中一种模式的解释。至于我关于游戏的例子,我看到这两种方法都在那个特定的情况下使用。因此,我没有具体说明。
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;
}