我正在編寫一個類的程序來顯示編碼冒泡排序的能力。我一直在努力工作好幾天,似乎無法得到它。至少現在它編譯,但拋出一個異常。
我評論了我遇到問題的部分,實際交換數組中的元素。冒泡排序拋出異常
該程序應該生成20個隨機整數的數組,然後使用冒泡排序對它們進行排序,打印每一遍,直到它完成。
import java.util.*;
public class BubbleSorting {
public static void bubbleSort(ArrayList<Integer> arr) {
int n = arr.size();
int temp = 0;
for (int i = 0; i < n; i++) {
//this is the chunk of code that I am having problems with
for (int j = i; j < (n-1); j++) {
if (arr.get(n-1) < arr.get(j))
temp = arr.get(j-1);
arr.set(j-1, arr.get(j));
arr.set(j, temp);
}
}
}
private static void printOut(int pass, ArrayList<Integer> array) {
System.out.print("Pass " + pass + ": ");
for (int i = 0; i < array.size() - 1; i++) {
System.out.print(array.get(i) + ", ");
}
System.out.print(array.get(array.size() - 1) + ".");
System.out.println();
}
public static void main(String[] args) {
ArrayList<Integer> array = new ArrayList<Integer>();
Scanner sc = new Scanner(System.in);
String userInput = "";
boolean endLoop = false;
do{
try{
for (int i = 0; i < 20; i++) {
int element = (int)(1000.0 * Math.random());
array.add(element);
}
System.out.print("\nUnsorted Array: ");
//Displays the unsorted ArrayList
for (int i = 0; i < array.size() - 1; i++) {
System.out.print(array.get(i) + ", ");
}
System.out.print(array.get(array.size() - 1) + ".");
System.out.println();
bubbleSort(array);
}
catch (IndexOutOfBoundsException e) {
System.out.println("\nThere is an out of bounds error in the ArrayList.");
}
System.out.print("\nEnter Y to continue or N to quit: ");
userInput = sc.nextLine();
if (userInput.equalsIgnoreCase("Y")) {
endLoop = false;
}
else if (userInput.equalsIgnoreCase("N")) {
endLoop = true;
}
else {
System.out.println("\nYou did not enter Y or N.");
System.out.println("Please try again.");
}
}while(endLoop == false);
}
}
什麼是例外? – bejado
您是否嘗試過使用您的調試器?或者手動跟蹤你的代碼?例如,當'i = j = 0'時需要交換條目時會發生什麼? –
當i = 0且j = 0時,您得到索引= -1,即索引超出範圍。因爲你的** j **從**我**開始。 – HappyHal