以下是使用 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 arr = [8, 4, 2, 9, 10, 3, 7, 5];
console.log(quickSort(arr));

该快速排序算法使用递归的方式进行排序。首先选择数组中的一个元素作为基准(pivot),然后将数组中小于基准的元素放在左边,大于基准的元素放在右边。然后对左右两个子数组分别递归执行同样的操作,直到子数组长度为1或为空。最后将排序好的左右子数组与基准合并起来,即得到排序后的结果

js 写个快排

原文地址: https://www.cveoy.top/t/topic/idP9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录