Java 冒泡排序算法实现详解
以下是 Java 中的冒泡排序实现:
public class BubbleSort {
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]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
public static void main(String[] args) {
int[] arr = {5, 1, 9, 3, 7, 4, 8, 6, 2};
bubbleSort(arr);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + ' ');
}
}
}
输出结果为:1 2 3 4 5 6 7 8 9
原文地址: https://www.cveoy.top/t/topic/nTDp 著作权归作者所有。请勿转载和采集!