【发布时间】:2017-07-04 22:51:21
【问题描述】:
我正在为类编写一个程序来展示编码冒泡排序的能力。我已经为此工作了几天,似乎无法得到它。至少现在它可以编译,但会引发异常。
我评论了我遇到问题的部分,即数组中元素的实际交换。
该程序应该生成一个由 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);
}
}
【问题讨论】:
-
有什么例外?
-
您是否尝试过使用调试器?还是手动遵循您的代码?例如,当您需要在
i = j = 0时交换条目时会发生什么? -
当 i = 0 且 j = 0 时,您会得到 index = -1,即索引超出范围。因为你的 j 从 i 开始。
-
它会抛出一个异常,但我不会费心告诉你它是什么......
标签: java arrays sorting bubble-sort