我只是对一个数组进行排序,我的代码看起来很好,但是我无法解决数组超出绑定异常。任何想法。
static void Main(string[] args)
{
int temp = 0; // For temporary holding array values for swapping
int [] num = new int[] {1, 4, 7, 6, 9, 3, 0, 8, 5, 2 };
for (int i = 0; i <= 9; i++) //Outer loop
{
for (int j = 0; j < 9; j++) // Inner loop
{
if (num[j] > num[j + 1])
{
temp = num[j + 1];
num[j + 1] = num[j];
num[j] = temp;
}
}
}
//Displaying the array
for (int i = 0; i < 9; i++)
Console.WriteLine(num[i]);
Console.ReadKey();
}
答案 0 :(得分:0)
将第二个循环修改为“j&lt; loopSize - i”(而不是j&lt; loopSize)将使冒泡排序的效率加倍。 :)
int[] num = new int[] { 1, 4, 7, 6, 9, 3, 0, 8, 5, 2 };
//int comparisons = 0;
int loopSize = num.Length - 1;
for (int i = 0; i <= loopSize; i++) //Outer loop
{
for (int j = 0; j < loopSize - i; j++) // Inner loop
{
//comparisons++;
if (num[j] > num[j + 1])
{
temp = num[j + 1];
num[j + 1] = num[j];
num[j] = temp;
}
}
}
//Displaying the array
for (int i = 0; i < num.Length; i++)
Console.WriteLine(num[i]);
//Console.WriteLine("comp: {0}", comparisons);
//Console.ReadKey();
}