gpt4 book ai didi

c# - 为什么这个插入排序会返回索引超出范围异常?

转载 作者:太空宇宙 更新时间:2023-11-03 19:41:33 24 4
gpt4 key购买 nike

出于某种原因,下面的 C# 插入排序代码返回索引超出范围异常。我会尝试将每个变量写到控制台,但异常不允许我这样做。我找不到解决方案,所以不胜感激。

using System;
using System.Collections.Generic;

class MainClass {
public static void Main (string[] args) {
int[] unsortedArray = {23, 19, 21, 44, 40, 60, 73, 80, 38, 55, 29, 78, 83, 61, 63, 9, 93, 6, 51, 11};
//Sets the unsorted list

Console.WriteLine ("Insertion Sort");
for (int i = 0; i < 20; i++) {
Console.Write(unsortedArray[i] + " , ");
}
//Displays a welcome message and the unsorted list

Console.WriteLine();
Console.WriteLine();
//Makes a gap between the unsorted and sorted list

List<int> sortedArray = new List<int>();
//Creates a new list for the sorted list

for (int i = 0; i < 19; i++) {
if (unsortedArray[i] < unsortedArray[i + 1]) {
sortedArray[i] = unsortedArray[i];
//If the next item in the unsorted list is less than or equal to the one after,
//it is added to the next spot in the sorted list.
}
else if (unsortedArray[i] > unsortedArray[i + 1]) {
sortedArray[i] = unsortedArray[i + 1];
//If the next item in the unsorted list is greater than the one after, it is
//moved behind one place and added to the sorted list before.
}
}


for (int i = 0; i < 19; i++) {
Console.Write(sortedArray[i] + ", ");
//Displays the sorted array
}

}
}

最佳答案

这可能是你的错误:

List<int> sortedArray = new List<int>();
// ..
sortedArray[i] = // ..

您不能在没有任何先前赋值的情况下为具有索引的 List 赋值。您要么需要将列表更改为数组,要么改用 add

此外:您不应该将列表对象命名为“array”,这只会让人感到困惑。

关于c# - 为什么这个插入排序会返回索引超出范围异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52568354/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com