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.

Click 'Start Sorting' to view animation

Algorithm Steps

  1. Start from the first element, compare adjacent pairs
  2. If the left element is larger, swap their positions
  3. Do the same for every adjacent pair from start to end
  4. After one pass, the largest element is at the end
  5. Repeat, reducing the comparison range each time
  6. Stop when no swaps occur in a pass

Time and Space Complexity

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,相等元素的相对顺序不会改变。

Use Cases

  • Teaching: As one of the simplest algorithms, great for beginners
  • Small datasets: When n < 50, simple implementation wins
  • Nearly sorted arrays: Efficient when data is almost sorted
  • Stability required: When preserving original order matters
Education Small Data Stable Sorting

Implementation

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]
    }
}