不知道是什么意思IndexOutOfRangeException
问题描述:
我试图在C#中插入排序算法,并努力修复该错误消息:不知道是什么意思IndexOutOfRangeException
“System.IndexOutOfRangeException”发生在algorithmsAssignment.exe”
只要它到达while循环,代码就会中断并给出消息。任何帮助,将不胜感激
(我不得不为我使用了一个二维数组字符串做string.compare
static void insertionSort(int columnSort, bool accendingOrder)
{
int column = columnSort - 1;
int i, j;
for (i = 1; i < dataArray.GetLength(1); i++)
{
string key = dataArray[column, i];
j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && string.Compare(dataArray[column, j - 1],
dataArray[j, column]) > 0)
{
dataArray[column, j + 1] = dataArray[column, j];
j = j - 1;
}
dataArray[column, j + 1] = key;
}
}
答
在你第一次迭代:(1 = 1)
string key = dataArray[column, i];
j = i - 1;
// J value is 0
while (j >= 0 && string.Compare(dataArray[column, j - 1], //Here, j - 1 = -1, since j = 0
....
....
我敢打赌,有你的索引超出范围,因为指数-1不可能存在。
干杯
答
你会得到错误对于i = 1,因为你有这样的条件:
j = i - 1; //j=0 for i=1
,并在错误的条件,而循环
while (j >= 0 && string.Compare(dataArray[column, j - 1],
dataArray[j, column]) > 0)
这个条件在while循环dataArray[column, j - 1]
将抛出IndexOutOfRange
例外,因为
j-1=-1 for j=0
我不想告诫你,但我认为你很有可能使用小于零的指数,或者大于或等于第索引数组。 –
您是否试图在文档中查找它?这是很好描述https://msdn.microsoft.com/en-Us/library/system.indexoutofrangeexception(v=vs.110).aspx – derpirscher