快速排序详解:从原理到实战

421 阅读3分钟

快速排序详解:从原理到实战

什么是快速排序?

快速排序(Quick Sort)是一种高效的排序算法,采用分治法(Divide and Conquer)策略。它通过选择一个“基准”元素,将数组分为两个子数组:小于基准的元素和大于基准的元素,然后递归地对这两个子数组进行排序。

快速排序的基本步骤

  1. 选择基准值:从数组中选择一个元素作为基准值。
  2. 分区操作:将所有比基准值小的元素移动到它的左边,比基准值大的元素移动到右边。
  3. 递归排序:对左右两个子数组分别重复上述过程,直到每个子数组只剩下一个元素为止。

快速排序的实现

Python 实现

def quick_sort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr) // 2]  # 选择中间元素作为基准
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    return quick_sort(left) + middle + quick_sort(right)

# 示例
arr = [3, 6, 8, 10, 1, 2, 1]
print(quick_sort(arr))  # 输出: [1, 1, 2, 3, 6, 8, 10]

Java 实现

public class QuickSort {
    public static void quickSort(int[] arr, int low, int high) {
        if (low < high) {
            int pi = partition(arr, low, high);
            quickSort(arr, low, pi - 1);
            quickSort(arr, pi + 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;
    }

    public static void main(String[] args) {
        int[] arr = {3, 6, 8, 10, 1, 2, 1};
        quickSort(arr, 0, arr.length - 1);
        for (int num : arr) {
            System.out.print(num + " ");
        }
        // 输出: 1 1 2 3 6 8 10
    }
}

JavaScript 实现

function quickSort(arr) {
    if (arr.length <= 1) {
        return arr;
    }
    const pivot = arr[arr.length - 1];
    const left = [];
    const right = [];
    for (let i = 0; i < arr.length - 1; i++) {
        if (arr[i] < pivot) {
            left.push(arr[i]);
        } else {
            right.push(arr[i]);
        }
    }
    return [...quickSort(left), pivot, ...quickSort(right)];
}

// 示例
const arr = [3, 6, 8, 10, 1, 2, 1];
console.log(quickSort(arr));  // 输出: [1, 1, 2, 3, 6, 8, 10]

快速排序的应用场景

场景描述:电商商品价格排序

假设你正在开发一个电商平台,用户可以在搜索页面上看到各种商品,并且可以根据价格进行排序。为了提高用户体验,你需要在后端对商品列表进行快速排序处理,以便用户可以立即看到按价格排序的结果。

数据结构设计

我们可以定义一个商品类 Product,包含名称和价格属性。

public class Product {
    private String name;
    private double price;

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

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }
}
快速排序的扩展实现

我们需要根据商品的价格字段进行排序,因此需要修改快速排序的比较逻辑。

import java.util.ArrayList;
import java.util.List;

public class ProductQuickSort {
    public static List<Product> quickSort(List<Product> products) {
        if (products.size() <= 1) {
            return products;
        }
        Product pivot = products.get(products.size() / 2);
        List<Product> left = new ArrayList<>();
        List<Product> middle = new ArrayList<>();
        List<Product> right = new ArrayList<>();
        for (Product product : products) {
            if (product.getPrice() < pivot.getPrice()) {
                left.add(product);
            } else if (product.getPrice() == pivot.getPrice()) {
                middle.add(product);
            } else {
                right.add(product);
            }
        }
        List<Product> sortedList = new ArrayList<>();
        sortedList.addAll(quickSort(left));
        sortedList.addAll(middle);
        sortedList.addAll(quickSort(right));
        return sortedList;
    }

    public static void main(String[] args) {
        List<Product> products = new ArrayList<>();
        products.add(new Product("Laptop", 999.99));
        products.add(new Product("Phone", 699.99));
        products.add(new Product("Tablet", 299.99));
        products.add(new Product("Headphones", 149.99));

        List<Product> sortedProducts = quickSort(products);
        for (Product product : sortedProducts) {
            System.out.println(product.getName() + ": $" + product.getPrice());
        }
        /*
         * 输出:
         * Headphones: $149.99
         * Tablet: $299.99
         * Phone: $699.99
         * Laptop: $999.99
         */
    }
}

在这个例子中,我们使用快速排序对商品列表进行了排序,使得用户可以根据价格快速找到他们感兴趣的商品。

总结

快速排序是一种非常高效且常用的排序算法,适用于大规模数据集。通过本文的学习,你应该已经掌握了快速排序的基本原理、不同编程语言的实现方式,以及如何将其应用于实际项目中。希望你在今后的工作或学习中能够灵活运用这一强大的工具!