最近刚开始学习C#,还请大家多多指教今天用C#写了个冒泡排序。虽然成功,但是却有一个疑问,希望老鸟或者高手能指导一下,3Q以下是代码:namespace BubbleSort
{
class Program
{
static void Main(string[] args)
{
int[] list = { 2, 6, 1, 90, 56, 34, 23, 344, 67, 100 };
Console.WriteLine("排序前:");
for (int i = 0; i < list.Length; i++)
Console.WriteLine(list[i]);
Console.WriteLine(); int temp; for (int i = 0; i < list.Length-7; i++)
for (int j = 0; j < list.Length-1; j++)
if (list[j] > list[j + 1])
{
temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
}
Console.WriteLine("排序后:");
for (int i = 0; i < list.Length; i++)
Console.WriteLine(list[i]);
Console.WriteLine(); }
}
}我的疑问是,今天无意把外循环的小于条件写成 < list.Length-1; 居然程序也得到了正确的结果,一般外循环大家都是写 < list.Length。 后来我不断的尝试,发现只要是外循环 < list.Length-7;以下的都对,就是说这个减去的数字只要是0~7都能得到结果,可就是当减8以后的数字就不行,不明白为什么会有这样的情况,希望各位能解释下,3Q
{
class Program
{
static void Main(string[] args)
{
int[] list = { 2, 6, 1, 90, 56, 34, 23, 344, 67, 100 };
Console.WriteLine("排序前:");
for (int i = 0; i < list.Length; i++)
Console.WriteLine(list[i]);
Console.WriteLine(); int temp; for (int i = 0; i < list.Length-7; i++)
for (int j = 0; j < list.Length-1; j++)
if (list[j] > list[j + 1])
{
temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
}
Console.WriteLine("排序后:");
for (int i = 0; i < list.Length; i++)
Console.WriteLine(list[i]);
Console.WriteLine(); }
}
}我的疑问是,今天无意把外循环的小于条件写成 < list.Length-1; 居然程序也得到了正确的结果,一般外循环大家都是写 < list.Length。 后来我不断的尝试,发现只要是外循环 < list.Length-7;以下的都对,就是说这个减去的数字只要是0~7都能得到结果,可就是当减8以后的数字就不行,不明白为什么会有这样的情况,希望各位能解释下,3Q
应该是这组数据在length -7轮以后恰好已经是正确顺序了 不能保证别的数据也这么巧
{
bool isNeed = false;
for (int j = 0; j < list.Length-1; j++)
if (list[j] > list[j + 1])
{
temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp; isNeed = true;
}
if (!isNeed)
{
break;
}
}
2, 6, 1, 90, 56, 34, 23, 344, 67, 100
2, 1,6, 56,34,23, 90, 67,100, 344 -- 1
1, 2,6, 34,23,56, 67,90,100, 344 -- 2
1, 2,6, 23,34,56, 67,90,100, 344 -- 3 OVER