public class BubbleSort {
public static void main(String[] args) {
int[] array = {3, 1, 6, 2, 4, 5};
bubbleSort(array);
System.out.println("排序后的数组:");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
public static void bubbleSort(int[] array) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (array[j] > array[j + 1]) {
// 交换 array[j] 和 array[j+1]
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
}
这段代码定义了一个名为`BubbleSort`的类,其中包含一个`main`方法用于测试冒泡排序算法,以及一个静态方法`bubbleSort`用于执行排序操作。在`main`方法中,我们创建了一个整数数组,并调用`bubbleSort`方法对其进行排序。排序完成后,我们打印出排序后的数组。
冒泡排序的基本思想是通过重复遍历要排序的列表,比较每对相邻元素,如果它们的顺序错误就把它们交换过来。遍历列表的工作重复进行直到没有再需要交换的元素为止,也就是说该列表已经排序完成。