代码实践
// 冒泡排序
static void bubbleSort(Comparable[] elements) {// 临时容器,用于变量交换值时存储Object temp;// 标志位 用于减少无意义的循环次数boolean flag;for (int i = 0; i < elements.length - 1; i++) {flag = false;for (int j = 0; j < elements.length - 1 - i; j++) {if (elements[j].compareTo(elements[j + 1]) > 0) {temp = elements[j];elements[j] = elements[j + 1];elements[j + 1] = (Comparable)temp;flag = true;}}// 为false说明已经排好序了,结束多余的循环即可if(flag == false){break;}}
}public static void main(String[] args) {// 准备10个可排序元素Scanner scanner = new Scanner(System.in);String[] arr = new String[10];for (int i = 0; i < arr.length; i++) {System.out.print("请输入第" + (i + 1) + "/" + arr.length + "个可排序元素:");arr[i] = scanner.nextLine();}// 执行冒泡排序bubbleSort(arr);// 输出排序后结果for (Object e : arr) {System.out.println(e);}
}