冒泡和快速排序的区别

冒泡算法

快速排序

时间复杂度

O(n^2)最坏/平均

O(nlog n )平均,O(n^2)最坏

空间复杂度

O(1)

O(log n)最好/O(n)最坏

稳定性

很稳定(元素顺序不变)

不稳定(元素顺序可能改变)

适用场景

小规模数据或接近有序的数据

大规模数据

核心思想

重复遍历,每轮都会把最大的元素移至末尾

选择基准值,比基准值小的元素放左边,大的放右边

代码实现对比 

1. 冒泡排序

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

 2. 快速排序

public static void quickSort(int[] arr, int low, int high) {
    if (low < high) {
        int pivotIndex = partition(arr, low, high);  // 分区
        quickSort(arr, low, pivotIndex - 1);         // 递归排序左半部分
        quickSort(arr, pivotIndex + 1, high);        // 递归排序右半部分
    }
}

private static int partition(int[] arr, int low, int high) {
    int pivot = arr[high];  // 选择最后一个元素作为基准值
    int i = low - 1;
    for (int j = low; j < high; j++) {
        if (arr[j] <= pivot) {
            i++;
            // 交换元素
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }
    // 将基准值放到正确位置
    int temp = arr[i + 1];
    arr[i + 1] = arr[high];
    arr[high] = temp;
    return i + 1;
}

你可能感兴趣的:(算法,数据结构)