我正在进行冒泡练习,我的感觉是非常接近正确。 就在此刻,我被呈现出一个永恒的循环。
错误在哪里?
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 + " ");
}
}
答案 0 :(得分:4)
C#中更好的方法是使用通用冒泡排序
public void BubbleSort<T>(IList<T> list);
{
BubbleSort<T>(list, Comparer<T>.Default);
}
public void BubbleSortImproved<T>(IList<T> list, IComparer<T> comparer)
{
bool stillGoing = true;
int k = 0;
while (stillGoing)
{
stillGoing = false;
for (int i = 0; i < list.Count - 1 - k; i++)
{
T x = list[i];
T y = list[i + 1];
if (comparer.Compare(x, y) > 0)
{
list[i] = y;
list[i + 1] = x;
stillGoing = true;
}
}
k++;
}
}
Jon Skeet在answer here中给出了该算法的简要说明。 “它使用任意比较器,但允许你省略它,在这种情况下,默认比较器用于相关类型。它将对IList的任何(非只读)实现进行排序,包括数组。”
我希望这会有所帮助。
答案 1 :(得分:3)
您与a
交换b
,但您不对输入数组执行任何操作。因此,您不断在内存中交换值,但原始数组不会更改。尝试:
for ( int i = 0; i < numbers.Length - 1; i++ )
{
if ( numbers[i] > numbers[i + 1] )
{
temporary = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i + 1] = temporary;
sorted = true;
}
}
答案 2 :(得分:2)
您没有将结果写回数组。
请改用:
//temporary = a;
//a = b;
//b = temporary;
numbers[i] = b;
numbers[i + 1] = a;
答案 3 :(得分:1)
应该是
if (numbers[i] > numbers[i + 1])
{
temporary = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i + 1] = temporary;
sorted = true;
}
a
,b
所做的更改并未反映在numbers[i]
numbers[i+1]
中,因为a和b仅为copy
numbers[i]
} numbers[i+1]
..
答案 4 :(得分:1)
以下是一个工作示例:
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++)
{
if (numbers[i] > numbers[i + 1])
{
temporary = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i + 1] = temporary;
sorted = true;
}
}
Console.WriteLine("sorted");
} while (sorted == true);
foreach (int i in numbers)
{
Console.Write(i + " ");
}
}