2012-11-25 68 views
0

我正在創建快速排序來對其他最接近特定城市的城市進行排序。我的Quicksort超出範圍

這裏是我的代碼:

private static void QuickSort(ArrayList<City> array, int First, int Last, City city){ 
    int Low,High,MidDistance; 
    Low = First; 
    High = Last; 
    Edge compareEdge = new Edge(array.get((First + Last)/ 2), city); 
    MidDistance = compareEdge.computeDistance(); 

    do { 
     compareEdge = new Edge(array.get(Low),city); 
     while (compareEdge.computeDistance() < MidDistance){ 
      Low += 1; 
      compareEdge = new Edge(array.get(Low),city); 
     } 

     compareEdge = new Edge(array.get(High),city); 
     while (compareEdge.computeDistance() > MidDistance){ 
      High -= 1; 
      compareEdge = new Edge(array.get(High),city); 
     } 

     if (Low <= High) { 
       Swap(array,Low,High); 
       Low = Low + 1; 
       High = High - 1; 
     } 

    } while (Low <= High); 

    if (First < High){ 
     QuickSort(array, First, High, city); 
    } 

    if (Low < Last){ 
     QuickSort(array, Low, Last, city); 
    } 

} 

private static void Swap(ArrayList<City>array,int Low, int High){ 
    City tempCtiy = array.get(Low); 
    array.get(Low).set(array.get(High)); 
    array.get(High).set(tempCtiy); 
} 

此代碼是我MST類中。所以,當我運行它

異常線程 「main」 java.lang.IndexOutOfBoundsException:指數:49,大小:49

它發生在這裏:

while (compareEdge.computeDistance() < MidDistance){ 
     Low += 1; 
     compareEdge = new Edge(array.get(Low),city); 
    } 

幫我弄清楚什麼是錯的。 當我在VB.net中編寫時,它運行良好。

回答

0

while添加終止條件上Low如下:

 while (compareEdge.computeDistance() < MidDistance && 
       && Low < array.size()-1){ 
       Low += 1; 
       compareEdge = new Edge(array.get(Low),city); 
     } 
+0

@KienPanda:如果這是有幫助的,請不要忘記接受的答案(箭頭標誌下方的投票)。 –

+0

我只有1個聲望,所以我不能投票。我標記了這個有用的答案。 :) –