C#中的数组越界异常

Array Out of Bound Exception in C#

我只是对数组进行排序,我的代码似乎没问题,但我无法解决数组越界异常。任何想法。

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();
}

将第二个循环修改为 "j < loopSize - i"(而不是 j < 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();
    }