버블 정렬을 코딩하는 기능을 보여주는 클래스 용 프로그램을 작성하고 있습니다. 나는 며칠 동안 그 일을 해왔으며 그것을 얻지 못하는 것 같습니다. 적어도 지금은 컴파일되지만 예외가 발생합니다.
배열에있는 요소의 실제 스와핑에 문제가있는 부분에 대해 주석을 달았습니다.버블 정렬에서 예외가 throw됩니다.
프로그램은 20 개의 randoms 정수 배열을 생성 한 다음 버블 정렬을 사용하여 정렬합니다. 완료 될 때까지 각 패스를 인쇄합니다.
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 ** ** ** i **부터 시작됩니다. – HappyHal