通过练习探索 JavaScript 基础

Beginner

This tutorial is from open-source community. Access the source code

简介

在这个实验中,我们将探索 JavaScript 编程的基础知识。通过一系列的练习和挑战,我们将涵盖变量、数据类型、函数、控制流等主题。在本实验结束时,你将对 JavaScript 语法有扎实的理解,并能够用这种通用的编程语言编写基本程序。

快速排序算法

为了练习编码,请打开终端/SSH 并输入node。此算法使用快速排序算法对数字数组进行排序。以下是具体步骤:

  • 使用递归。
  • 使用展开运算符(...)克隆原始数组arr
  • 如果数组的length小于2,则返回克隆后的数组。
  • 使用Math.floor()计算枢轴元素的索引。
  • 使用Array.prototype.reduce()Array.prototype.push()将数组拆分为两个子数组。第一个子数组包含小于或等于枢轴的元素,第二个子数组包含大于它的元素。将结果解构为两个数组。
  • 对创建的子数组递归调用quickSort()

以下是实现此算法的示例:

const quickSort = (arr) => {
  const a = [...arr];
  if (a.length < 2) return a;
  const pivotIndex = Math.floor(arr.length / 2);
  const pivot = a[pivotIndex];
  const [lo, hi] = a.reduce(
    (acc, val, i) => {
      if (val < pivot || (val === pivot && i != pivotIndex)) {
        acc[0].push(val);
      } else if (val > pivot) {
        acc[1].push(val);
      }
      return acc;
    },
    [[], []]
  );
  return [...quickSort(lo), pivot, ...quickSort(hi)];
};

要测试它,请运行以下命令:

quickSort([1, 6, 1, 5, 3, 2, 1, 4]); // [1, 1, 1, 2, 3, 4, 5, 6]

总结

恭喜你!你已经完成了快速排序实验。你可以在 LabEx 中练习更多实验来提升你的技能。