快速排序完全指南:原理 + 代码 + 应用场景

243 阅读3分钟

快速排序完全指南:原理 + 代码 + 应用场景

一、快速排序简介 🎯

快速排序(Quick Sort)是一种基于分治思想的经典排序算法。它的核心思想是:选择一个基准值(pivot),将数组分为两部分,左边的元素都比基准值小,右边的元素都比基准值大,然后递归地对左右两部分进行相同的操作。

快速排序的时间复杂度为 O(n log n),在大多数情况下表现非常优秀,因此被广泛应用于各种场景。

二、快速排序的原理

  1. 选择基准值:通常选择数组的第一个元素或最后一个元素作为基准值。
  2. 分区操作:将数组中小于基准值的元素放到左边,大于基准值的元素放到右边。
  3. 递归排序:对左右两部分分别重复上述步骤,直到子数组长度为 1 或 0。

三、代码实现

1. Java 实现

public class QuickSort {
    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++;
                swap(arr, i, j);
            }
        }
        swap(arr, i + 1, high);
        return i + 1;
    }

    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}

2. Python 实现

def quick_sort(arr):
    if len(arr) <= 1:
        return arr
    else:
        pivot = arr[0]
        less_than_pivot = [x for x in arr[1:] if x <= pivot]
        greater_than_pivot = [x for x in arr[1:] if x > pivot]
        return quick_sort(less_than_pivot) + [pivot] + quick_sort(greater_than_pivot)

# 示例
print(quick_sort([3, 6, 8, 10, 1, 2, 1]))

四、应用场景设计:电商价格排序

假设你正在开发一个电商网站,用户希望根据商品价格进行升序或降序排序。我们可以使用快速排序来实现这一功能。

1. 场景描述

用户在商品列表页面点击“价格排序”按钮时,系统需要按照价格对商品进行排序,并重新渲染页面。

2. 实现步骤

  1. 获取商品列表数据(包括商品名称和价格)。
  2. 使用快速排序对商品价格进行排序。
  3. 将排序后的结果返回给前端展示。

3. 示例代码

// 商品类定义
public class Product {
    private String name;
    private double price;

    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public double getPrice() {
        return price;
    }

    public String getName() {
        return name;
    }
}

// 快速排序商品价格
public class ProductSorter {
    public static void sortProductsByPrice(List<Product> products) {
        quickSort(products, 0, products.size() - 1);
    }

    private static void quickSort(List<Product> products, int low, int high) {
        if (low < high) {
            int pivotIndex = partition(products, low, high);
            quickSort(products, low, pivotIndex - 1);
            quickSort(products, pivotIndex + 1, high);
        }
    }

    private static int partition(List<Product> products, int low, int high) {
        double pivot = products.get(high).getPrice();
        int i = low - 1;
        for (int j = low; j < high; j++) {
            if (products.get(j).getPrice() < pivot) {
                i++;
                swap(products, i, j);
            }
        }
        swap(products, i + 1, high);
        return i + 1;
    }

    private static void swap(List<Product> products, int i, int j) {
        Collections.swap(products, i, j);
    }
}

// 测试代码
List<Product> productList = new ArrayList<>();
productList.add(new Product("iPhone 14", 7999));
productList.add(new Product("Samsung Galaxy S23", 6999));
productList.add(new Product("Xiaomi 13", 4499));
ProductSorter.sortProductsByPrice(productList);
for (Product product : productList) {
    System.out.println(product.getName() + " - " + product.getPrice());
}

五、总结

快速排序作为一种高效的排序算法,在实际开发中有着广泛的应用。无论是简单的数组排序还是复杂的业务场景,掌握快速排序都能让你事半功倍!🌟