代码:
// 冒泡排序算法
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入多个数字,以逗号,分开:");
String str = scanner.next();
String[] strs = str.split(",");
int[] arr = new int[strs.length];
for (int i = 0; i < strs.length; i++) {
arr[i] = Integer.parseInt(strs[i]);
}
System.out.println("请选择排序方式,使用升序排序请输入1,使用降序排序请输入2:");
int method = scanner.nextInt();
boolean asc = method == 1;
sort(arr, asc);
System.out.println("---------" + (asc ? "升序排序" : "降序排序") + "结果如下---------");
for (int j : arr) {
System.out.print(j + " ");
}
}
public static void sort(int[] arr, boolean asc) {
boolean exchange = true;
for (int i = 1; i < arr.length && exchange; i++) {
exchange = false;
for (int j = 0; j < arr.length - 1; j++) {
if (asc ? arr[j] > arr[j + 1] : arr[j] < arr[j + 1]) {
int temp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = temp;
exchange = true;
}
}
}
}
}
结果:
请输入多个数字,以逗号,分开:
1,2,4,24,1,32,33333,2
请选择排序方式,使用升序排序请输入1,使用降序排序请输入2:
2
---------降序排序结果如下---------
33333 32 24 4 2 2 1 1