Watch elements float up like bubbles to their correct positions
Bubble Sort is a simple and intuitive sorting algorithm. It repeatedly traverses the list, compares adjacent elements, and swaps them if they're in the wrong order. After each pass, the largest element 'bubbles up' to the end, like bubbles rising in water.
| Case | Time Complexity | Description |
|---|---|---|
| Best Case | O(n) | Array is already sorted, only one pass needed |
| Average Case | O(n²) | Multiple passes and swaps required |
| Worst Case | O(n²) | Array is in reverse order |
| Space Complexity | O(1) | Only constant extra space needed (in-place) |
冒泡排序是Stable Sort,相等元素的相对顺序不会改变。
def bubble_sort(arr): """冒泡排序算法""" n = len(arr) for i in range(n): swapped = False # 每轮将最大元素"冒泡"到末尾 for j in range(0, n - i - 1): if arr[j] > arr[j + 1]: # 交换相邻元素 arr[j], arr[j + 1] = arr[j + 1], arr[j] swapped = True # 如果没有交换发生,数组已有序 if not swapped: break return arr # 使用示例 arr = [64, 34, 25, 12, 22, 11, 90] print(bubble_sort(arr)) # 输出: [11, 12, 22, 25, 34, 64, 90]
public class BubbleSort { /** * 冒泡排序算法 * @param arr 待排序数组 */ public static void bubbleSort(int[] arr) { int n = arr.length; for (int i = 0; i < n - 1; i++) { boolean swapped = false; // 每轮将最大元素"冒泡"到末尾 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; swapped = true; } } // 如果没有交换发生,数组已有序 if (!swapped) { break; } } } public static void main(String[] args) { int[] arr = {64, 34, 25, 12, 22, 11, 90}; bubbleSort(arr); System.out.println(Arrays.toString(arr)); // 输出: [11, 12, 22, 25, 34, 64, 90] } }