【发布时间】:2012-11-24 06:55:57
【问题描述】:
我正在做一个冒泡排序练习,我的感觉是它非常接近正确。 就像现在一样,我看到了一个永恒的循环。
错在哪里?
static void Main(string[] args)
{
int[] numbers = { 2, 4, 8, 5, 88, 55, 32, 55, 47, 8, 99, 120, 4, 32 };
int temporary;
bool sorted;
do
{
sorted = false;
for (int i = 0; i < numbers.Length - 1; i++)
{
int a = numbers[i];
int b = numbers[i + 1];
if (a > b)
{
temporary = a;
a = b;
b = temporary;
sorted = true;
}
}
Console.WriteLine("sorted");
} while (sorted == true);
foreach (int i in numbers)
{
Console.Write(i + " ");
}
}
【问题讨论】:
-
@Killercam 我认为问题表明这是一个竞争条件。
-
酷。向所有人道歉... :'[
-
您的循环总是在每次迭代中运行 1 到多次(以及该堆栈)。每次迭代都需要将结束条件减少 1。因此,您应该编写变量(具有 numbers.length)并在条件下编写 i
标签: c# bubble-sort