2017-05-03 74 views
-1

我試圖在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; 
     } 
    } 
+3

我不想告誡你,但我認爲你很有可能使用小於零的指數,或者大於或等於第索引數組。 –

+1

您是否試圖在文檔中查找它?這是很好描述https://msdn.microsoft.com/en-Us/library/system.indexoutofrangeexception(v=vs.110).aspx – derpirscher

回答

1

在你第一次迭代:(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不可能存在。

乾杯

0

你會得到錯誤對於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