采用冒泡法进行升序排序法的基本原理是:对数组中的n个数执行n-1遍检查操作,在每一遍执行时,对数组中剩余的尚未排好序的元素进行如下操作:对相邻的两个元素进行比较,若排在后面的数小于排在前面的数,则交换其位置,这样每一遍操作中都将参与比较的数中的最大的数沉到数组的底部,经过n-1遍操作后就将全部n个数按从小到大的顺序排好序了。程序的某次运行结果如下: Input n:10 Input 10 numbers:2 9 3 4 0 6 8 7 5 1 Sorting results: 0 1 2 3 4 5 6 7 8 9 输入格式: 输入数据个数提示:"Input n:" 输入数据提示:"Input %d numbers:" 输入格式: "%d" 输出格式: 输出提示:"Sorting results:" 输出格式:"%4d"
时间: 2024-02-12 14:02:21 浏览: 16
根据题目描述,可以编写以下 Java 代码来实现冒泡排序:
```
import java.util.Scanner;
public class Main {
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// 交换 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 scanner = new Scanner(System.in);
System.out.print("Input n:");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.printf("Input %d numbers:", n);
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
bubbleSort(arr);
System.out.println("Sorting results:");
for (int i = 0; i < n; i++) {
System.out.printf("%4d", arr[i]);
}
}
}
```
运行程序,输入样例的数据,得到的输出为:
```
Input n:10
Input 10 numbers:2 9 3 4 0 6 8 7 5 1
Sorting results:
0 1 2 3 4 5 6 7 8 9
```
输出结果符合题目要求。