我正在创建快速排序以对距离特定城市最近的其他城市进行排序。
这是我的代码:
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 :(得分:0)
在while
Low
上添加终止条件,如下所示:
while (compareEdge.computeDistance() < MidDistance &&
&& Low < array.size()-1){
Low += 1;
compareEdge = new Edge(array.get(Low),city);
}