joken-前端工程师

  :: 首页 :: 博问 :: 闪存 :: 新随笔 :: :: :: 管理 ::

在JavaScript中实现快速排序可以通过递归方式来完成。下面是一个示例代码:

function quickSort(arr) {
    // 如果数组为空或只有一个元素,则无需排序
    if (arr.length <= 1) {
        return arr;
    }

    // 选择基准元素(这里选择中间元素)
    const pivotIndex = Math.floor(arr.length / 2);
    const pivot = arr[pivotIndex];

    // 初始化左右数组
    const left = [];
    const right = [];

    // 遍历数组,将元素根据基准值分到左右数组中
    for (let i = 0; i < arr.length; i++) {
        if (i === pivotIndex) continue; // 跳过基准元素
        if (arr[i] < pivot) {
            left.push(arr[i]);
        } else {
            right.push(arr[i]);
        }
    }

    // 递归对左右数组进行排序,并合并结果
    return [...quickSort(left), pivot, ...quickSort(right)];
}

// 示例使用
const unsortedArray = [3, 6, 8, 10, 1, 2, 1];
const sortedArray = quickSort(unsortedArray);
console.log(sortedArray);

解释

  1. 基本条件检查

    • 如果数组的长度小于等于1,直接返回数组,因为这种情况下不需要排序。
  2. 选择基准元素

    • 使用数组的中间元素作为基准值(pivot)。
  3. 分割数组

    • 初始化两个空数组 leftright
    • 遍历原数组,除了基准元素之外,将小于基准值的元素放入 left,大于或等于基准值的元素放入 right
  4. 递归排序和合并

    • leftright 数组递归地调用 quickSort
    • 合并排序后的左数组、基准元素和右数组。

这种实现方式是比较直观和简洁的,但对于非常大的数组或递归深度较大的情况,可以考虑优化基准选择和递归方式,以避免栈溢出或性能问题。

原理图

Initial Array: [3, 6, 8, 10, 1, 2, 1]
        |
Pivot: 3
       / \
Left: [1, 2, 1]  Right: [6, 8, 10]
       / \                / \
     Pivot: 1          Pivot: 6
      /   \                / \
Left: [] Right: [2, 1]  Left: [] Right: [8, 10]
         / \                      / \
      Pivot: 2                  Pivot: 8
       /    \                    /     \
Left: [1]  Right: []  Left: [] Right: [10]

Combining:
[1, 1, 2] + 3 + [6, 8, 10]

Final Sorted Array:
[1, 1, 2, 3, 6, 8, 10]

总结

快速排序就是递归分为左右2个数组,以中间值为基准拆分大小左右2边数组,不断递归此过程,此过程已排序,实际就是由大范围到小范围的排序过程,然后再一层一层的合并上来。最后得到排序结果的总的数组。

posted on 2024-07-14 10:00  joken1310  阅读(1)  评论(0编辑  收藏  举报