冒泡排序的基本思想是:每次比较两个相邻的元素,如果它们的顺序错误就把它们交换过来。
public class BubbleSortExample {
public static void main(String[] args) {
int[] array = {64, 34, 25, 12, 22, 11, 90};
System.out.println("排序前的数组:");
printArray(array);
bubbleSort(array);
System.out.println("排序后的数组:");
printArray(array);
}
// 冒泡排序
public static void bubbleSort(int[] array) {
int n = array.length;
boolean swapped;
for (int i = 0; i < n - 1; i++) {
swapped = false;
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;
swapped = true;
}
}
// 如果没有发生交换,说明数组已经有序,提前退出
if (!swapped) {
break;
}
}
}
// 打印数组
public static void printArray(int[] array) {
for (int i : array) {
System.out.print(i + " ");
}
System.out.println();
}
}
bubbleSort时间复杂度:
第一个循环O(n-1)
第二个循环O(n-1 + n-2 +n-3 +....1)
O(n-1+n^2/2 )=O(n^2)
bubbleSort空间复杂度:只需要借助一个temp,
O(1)
这种排序空间复杂度较堆排序少,但是时间复杂度高
那还有没有更好的排序算法呢?
答案:不要走开,请看下节——快速排序。