Java可以尝试写下智能排序菜单程序(数组、冒泡排序算法)
时间: 2023-12-24 10:02:09 浏览: 30
当然可以,以下是一个简单的智能排序菜单程序,使用了数组和冒泡排序算法:
```java
import java.util.Scanner;
public class IntelligentSortMenu {
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] arr = null;
while (true) {
System.out.println("请选择要进行的操作:");
System.out.println("1. 输入数组");
System.out.println("2. 对数组进行排序");
System.out.println("3. 退出程序");
System.out.print("请输入选项: ");
String choice = input.nextLine();
if (choice.equals("1")) {
System.out.print("请输入数组长度: ");
int n = input.nextInt();
arr = new int[n];
System.out.println("请输入数组元素:");
for (int i = 0; i < n; i++) {
arr[i] = input.nextInt();
}
input.nextLine(); //清除输入缓存
System.out.println("输入的数组为: " + Arrays.toString(arr));
} else if (choice.equals("2")) {
if (arr == null) {
System.out.println("请先输入数组!");
} else {
System.out.println("排序前的数组为: " + Arrays.toString(arr));
bubbleSort(arr);
System.out.println("排序后的数组为: " + Arrays.toString(arr));
}
} else if (choice.equals("3")) {
System.out.println("程序已退出");
break;
} else {
System.out.println("无效选项,请重新输入");
}
}
}
}
```
这个程序首先定义了一个 `bubbleSort` 方法,用于对传入的数组进行冒泡排序。然后进入一个无限循环,根据用户的选择进行不同的操作。当用户选择输入数组时,程序会提示用户输入数组的长度和每个元素的值,然后将输入的数组存储在 `arr` 数组中。当用户选择对数组进行排序时,程序会先判断 `arr` 是否为空,如果为空则提示用户先输入数组,否则调用 `bubbleSort` 方法进行排序并输出结果。当用户选择退出程序时,程序会结束循环并退出。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)