用java写一个冒泡排序的例子要求能运行。
以下是一个使用Java语言实现的冒泡排序例子:
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) {
int[] arr = {5, 2, 6, 1, 3, 9, 4, 8, 7};
bubbleSort(arr);
System.out.println(Arrays.toString(arr)); // 输出:[1, 2, 3, 4, 5, 6, 7, 8, 9]
}
该例子中,bubbleSort()方法接收一个整型数组作为参数,对该数组进行冒泡排序,并将排序后的数组返回。main()方法中定义了一个整型数组并对其进行排序,最终输出排序后的结果
原文地址: https://www.cveoy.top/t/topic/eous 著作权归作者所有。请勿转载和采集!