我想打印带有随机数的气泡排序数组



>我创建了一个名为 place 的数组,并用 1 到 100 的随机数填充所有 100 个索引,并在数组上运行气泡排序。当我想在控制台中打印出来时,它什么也没提供。都是空白的。注意,我对 C# 和一般编程很陌生,所以如果你能告诉我为什么这个东西不打印我的排序数组,我将不胜感激。

static void Main(string[] args)
    {
        Random random = new Random();
        int[] place = new int[100];
        int spot = random.Next(1, 101);
        for (int i = 0; i < place.Length; i++)
        {
            spot = random.Next(1, 101);
            place[i] = spot;
        }
        for (int i = 0; i <= place.Length; i++) 
        {
            for (int j = 0; j < place.Length - 1; i++) 
            {
                if (place[j] > place[j + 1])
                {
                    int temp = place[j + 1];
                    place[j + 1] = place[j];
                    place[j] = temp;
                }
            }
            Console.WriteLine(place[i]);
        }
        Console.ReadKey();
    }

您有两个拼写错误:

for (int i = 0; i < place.Length; i++) // should be <, not <= (throws exception)
{
    for (int j = 0; j < place.Length - 1; j++) // should be j++ instead of i++
    {
        if (place[j] > place[j + 1])
        {
            int temp = place[j + 1];
            place[j + 1] = place[j];
            place[j] = temp;
        }    
    }
    Console.WriteLine(place[i]); // is it necessary?
}
Console.WriteLine();
for (int i = 0; i < place.Length; i++)
{
    Console.WriteLine(place[i]);
}

我还添加了打印整个数组的代码,以查看这种排序是否有效(确实如此(。

最新更新