バブルソートをコード化する能力を示すために、クラス用のプログラムを作成しています。私は数日間それに取り組んでおり、それを得ることができない。少なくとも今はコンパイルされますが、例外がスローされます。
私は、問題を抱えている部分、配列内の要素の実際の入れ替えについてコメントしました。バブルソート例外をスローする
プログラムは、ランダムな整数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のときは、インデックスの範囲外のインデックスを取得します。あなたの** j **は** i **から始まるからです。 – HappyHal