出于某种原因,下面的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
}
}
}
Run Code Online (Sandbox Code Playgroud)
这可能是你的错误:
List<int> sortedArray = new List<int>();
// ..
sortedArray[i] = // ..
Run Code Online (Sandbox Code Playgroud)
您无法为List没有任何先前分配的索引分配值.您需要将列表更改为数组或使用add.
也; 你不应该将列表对象命名为"数组",它只会让人感到困惑.