图解经典排序


0 算法概述

0.1 算法分类

十种常见排序算法可以分为两大类:

非线性时间比较类排序: 通过比较来决定元素间的相对次序,由于其时间复杂度不能突破 O(nlog2n), 因此称为非线性时间比较类排序。

线性时间非比较类排序: 不通过比较来决定元素间的相对次序,它可以突破基于比较排序的时间下界,以线性时间运行,因此称为线性时间非比较类排序。

排序算法分类

0.2 算法复杂度

算法复杂度

0.3 相关概念

稳定: 如果 a 原本在 b 前面,且 a=b, 排序之后 a 仍然在 b 的前面。

不稳定: 如果 a 原本在 b 的前面,且 a=b, 排序之后 a 可能会出现在 b 的后面。

时间复杂度: 对排序数据的总的操作次数。反映当 n 变化时,操作次数呈现什么规律。

空间复杂度: 是指算法在计算机内执行时所需存储空间的度量,它也是数据规模 n 的函数。

1 冒泡排序 (Bubble Sort)

冒泡排序是一种简单的排序算法。它重复地走访过要排序的数列,一次比较两个元素,如果它们的顺序错误就把它们交换过来。走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。这个算法的名字由来是因为越小的元素会经由交换慢慢 “浮” 到数列的顶端。

1.1 算法描述

  • 比较相邻的元素。如果第一个比第二个大,就交换它们两个;
  • 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对,这样在最后的元素应该会是最大的数;
  • 针对所有的元素重复以上的步骤,除了最后一个;
  • 重复步骤 1~3, 直到没有任何一对数字需要比较。

1.2 动图演示

冒泡排序

1.3 代码实现

Sorts an array of numbers, using the bubble sort algorithm.

  • Declare a variable, swapped, that indicates if any values were swapped during the current iteration.
  • Use the spread operator (...) to clone the original array, arr.
  • Use a for loop to iterate over the elements of the cloned array, terminating before the last element.
  • Use a nested for loop to iterate over the segment of the array between 0 and i, swapping any adjacent out of order elements and setting swapped to true.
  • If swapped is false after an iteration, no more changes are needed, so the cloned array is returned.
const bubbleSort = (arr) => {
  let swapped = false;
  const a = [...arr];
  for (let i = 1; i < a.length - 1; i++) {
    swapped = false;
    for (let j = 0; j < a.length - 1 - i; j++) {
      if (a[j + 1] < a[j]) {
        [a[j], a[j + 1]] = [a[j + 1], a[j]];
        swapped = true;
      }
    }
    if (!swapped) return a;
  }
  return a;
};

bubbleSort


const bubbleSort = (arr) => {
  const a = [...arr];
  let i = a.length;
  while (i > 0) {
    for (let j = 0; j < i - 1; j++) {
      if (a[j] > a[j + 1]) {
        [a[j], a[j + 1]] = [a[j + 1], a[j]];
      }
    }
    i--;
  }
  return a;
};

1.4 算法分析

  • 冒泡排序比较所有相邻的两个项,如果第一个比第二个大,则交换它们。
  • 内层循环减去 i 的原因:从内循环减去外循环中已跑过的轮数,就可以避免内循环中所有不必要的比较。

冒泡排序

2 选择排序 (Selection Sort)

选择排序 (Selection-sort) 是一种简单直观的排序算法。它的工作原理:首先在未排序序列中找到最小 (大) 元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小 (大) 元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。

2.1 算法描述

n 个记录的直接选择排序可经过 n-1 趟直接选择排序得到有序结果。具体算法描述如下:

  • 初始状态:无序区为 R[1..n], 有序区为空;
  • 第 i 趟排序 (i=1,2,3…n-1) 开始时,当前有序区和无序区分别为 R[1..i-1]R[i..n]. 该趟排序从当前无序区中 - 选出关键字最小的记录 R[min], 将它与无序区的第 1 个记录 R[i] 交换,使 R[1..i]R[i+1..n] 分别变为记录个数增加 1 个的新有序区和记录个数减少 1 个的新无序区;
  • n-1 趟结束,数组有序化了。

2.2 动图演示

选择排序

2.3 代码实现

const selectionSort = (arr) => {
  const len = arr.length;
  let minIndex;
  for (let i = 0; i < len - 1; i++) {
    minIndex = i;
    for (let j = i + 1; j < len; j++) {
      if (arr[j] < arr[minIndex]) {
        // 寻找最小的数
        minIndex = j; // 将最小数的索引保存
      }
    }
    [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
  }
  return arr;
};

Sorts an array of numbers, using the selection sort algorithm.

  • Use the spread operator (...) to clone the original array, arr.
  • Use a for loop to iterate over elements in the array.
  • Use Array.prototype.slice() and Array.prototype.reduce() to find the index of the minimum element in the subarray to the right of the current index and perform a swap, if necessary.
const selectionSort = (arr) => {
  const a = [...arr];
  for (let i = 0; i < a.length; i++) {
    const min = a.slice(i + 1).reduce((acc, val, j) => (val < a[acc] ? j + i + 1 : acc), i);
    if (min !== i) [a[i], a[min]] = [a[min], a[i]];
  }
  return a;
};

// Examples
selectionSort([5, 1, 4, 2, 3]); // [1, 2, 3, 4, 5]

selectionSort

2.4 算法分析

表现最稳定的排序算法之一,因为无论什么数据进去都是 O(n2) 的时间复杂度,所以用到它的时候,数据规模越小越好。唯一的好处可能就是不占用额外的内存空间了吧。理论上讲,选择排序可能也是平时排序一般人想到的最多的排序方法了吧。

选择排序

3 插入排序 (Insertion Sort)

插入排序 (Insertion-Sort) 的算法描述是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。

3.1 算法描述

一般来说,插入排序都采用 in-place 在数组上实现。具体算法描述如下:

  • 从第一个元素开始,该元素可以认为已经被排序;
  • 取出下一个元素,在已经排序的元素序列中从后向前扫描;
  • 如果该元素 (已排序) 大于新元素,将该元素移到下一位置;
  • 重复步骤 3, 直到找到已排序的元素小于或者等于新元素的位置;
  • 将新元素插入到该位置后;
  • 重复步骤 2~5.

3.2 动图演示

插入排序

3.3 代码实现

Sorts an array of numbers, using the insertion sort algorithm.

  • Use Array.prototype.reduce() to iterate over all the elements in the given array.
  • If the length of the accumulator is 0, add the current element to it.
  • Use Array.prototype.some() to iterate over the results in the accumulator until the correct position is found.
  • Use Array.prototype.splice() to insert the current element into the accumulator.
const insertionSort = (arr) =>
  arr.reduce((acc, x) => {
    if (!acc.length) return [x];
    acc.some((y, j) => {
      if (x <= y) {
        acc.splice(j, 0, x);
        return true;
      }
      if (x > y && j === acc.length - 1) {
        acc.splice(j + 1, 0, x);
        return true;
      }
      return false;
    });
    return acc;
  }, []);

insertionSort


const insertionSort = (arr) => {
  const len = arr.length;
  let preIndex, current;
  for (let i = 1; i < len; i++) {
    preIndex = i - 1;
    current = arr[i];
    while (preIndex >= 0 && arr[preIndex] > current) {
      arr[preIndex + 1] = arr[preIndex];
      preIndex--;
    }
    arr[preIndex + 1] = current;
  }
  return arr;
};

3.4 算法分析

插入排序在实现上,通常采用 in-place 排序 (即只需用到 O(1) 的额外空间的排序), 因而在从后向前扫描过程中,需要反复把已排序元素逐步向后挪位,为最新元素提供插入空间。

  • 假定第一项已经排序了。
  • 后内层循环对当前元素前面有序表进行待插入位置查找,并进行移动。

插入排序

4 希尔排序 (Shell Sort)

1959 年 Shell 发明,第一个突破 O(n2) 的排序算法,是简单插入排序的改进版。它与插入排序的不同之处在于,它会优先比较距离较远的元素。希尔排序又叫 缩小增量排序.

4.1 算法描述

先将整个待排序的记录序列分割成为若干子序列分别进行直接插入排序,具体算法描述:

  • 选择一个增量序列 t1,t2,…,tk, 其中 ti>tj,tk=1;
  • 按增量序列个数 k, 对序列进行 k 趟排序;
  • 每趟排序,根据对应的增量 ti, 将待排序列分割成若干长度为 m 的子序列,分别对各子表进行直接插入排序。仅增量因子为 1 时,整个序列作为一个表来处理,表长度即为整个序列的长度。

4.2 动图演示

希尔排序

4.3 代码实现

function shellSort(arr) {
  var gap, i, j;
  var temp;
  for (gap = arr.length >> 1; gap > 0; gap >>= 1) {
    for (i = gap; i < arr.length; i++) {
      temp = arr[i];
      for (j = i - gap; j >= 0 && arr[j] > temp; j -= gap) {
        arr[j + gap] = arr[j];
      }
      arr[j + gap] = temp;
    }
  }
  return arr;
}

Right shift assignment (>>=)

Right shift (>>)

4.4 算法分析

希尔排序的核心在于间隔序列的设定。既可以提前设定好间隔序列,也可以动态的定义间隔序列。动态定义间隔序列的算法是《算法 (第 4 版)》的合著者 Robert Sedgewick 提出的。

希尔排序

5 归并排序 (Merge Sort)

归并排序是建立在归并操作上的一种有效的排序算法。该算法是采用分治法 (Divide and Conquer) 的一个非常典型的应用。将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。若将两个有序表合并成一个有序表,称为 2 - 路归并。

5.1 算法描述

  • 把长度为 n 的输入序列分成两个长度为 n/2 的子序列;
  • 对这两个子序列分别采用归并排序;
  • 将两个排序好的子序列合并成一个最终的排序序列。

5.2 动图演示

归并排序

5.3 代码实现

Sorts an array of numbers, using the merge sort algorithm.

  • Use recursion.
  • If the length of the array is less than 2, return the array.
  • Use Math.floor() to calculate the middle point of the array.
  • Use Array.prototype.slice() to slice the array in two and recursively call mergeSort() on the created subarrays.
  • Finally, use Array.from() and Array.prototype.shift() to combine the two sorted subarrays into one.
const mergeSort = (arr) => {
  if (arr.length < 2) return arr;
  const mid = Math.floor(arr.length / 2);
  const l = mergeSort(arr.slice(0, mid));
  const r = mergeSort(arr.slice(mid, arr.length));
  return Array.from({ length: l.length + r.length }, () => {
    if (!l.length) return r.shift();
    else if (!r.length) return l.shift();
    else return l[0] > r[0] ? r.shift() : l.shift();
  });
};

mergeSort

5.4 算法分析

归并排序是一种稳定的排序方法。和选择排序一样,归并排序的性能不受输入数据的影响,但表现比选择排序好的多,因为始终都是 O(nlog2n) 的时间复杂度。代价是需要额外的内存空间。

归并排序

6 快速排序 (Quick Sort)

快速排序的基本思想:通过一趟排序将待排记录分隔成独立的两部分,其中一部分记录的关键字均比另一部分的关键字小,则可分别对这两部分记录继续进行排序,以达到整个序列有序。

6.1 算法描述

快速排序使用分治法来把一个串 (list) 分为两个子串 (sub-lists). 具体算法描述如下:

  • 从数列中挑出一个元素,称为 “基准”(pivot);
  • 重新排序数列,所有元素比基准值小的摆放在基准前面,所有元素比基准值大的摆在基准的后面 (相同的数可以到任一边). 在这个分区退出之后,该基准就处于数列的中间位置。这个称为分区 (partition) 操作;
  • 递归地 (recursive) 把小于基准值元素的子数列和大于基准值元素的子数列排序。

6.2 动图演示

快速排序

6.3 代码实现

  • Use recursion.
  • Use the spread operator (...) to clone the original array, arr.
  • If the length of the array is less than 2, return the cloned array.
  • Use Math.floor() to calculate the index of the pivot element.
  • Use Array.prototype.reduce() and Array.prototype.push() to split the array into two subarrays (elements smaller or equal to the pivot and elements greater than it), destructuring the result into two arrays.
  • Recursively call quickSort() on the created subarrays.
// 💯
const quickSort = (arr) => {
  const a = [...arr];
  if (a.length < 2) return a;
  const pivotIndex = Math.floor(arr.length / 2);
  const pivot = a[pivotIndex];
  const [left, right] = 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(left), pivot, ...quickSort(right)];
};

quickSort

// 简化版
const quickSort = (arr) => {
  const a = [...arr];
  if (arr.length <= 1) return arr;
  const pivotIndex = Math.floor(arr.length / 2);
  const pivot = a.splice(pivotIndex, 1)[0];
  const [left, right] = a.reduce(
    (acc, cur) => {
      cur < pivot ? acc[0].push(cur) : acc[1].push(cur);
      return acc;
    },
    [[], []],
  );
  return quickSort(left).concat(pivot, quickSort(right));
};

// 简化版-2
const quickSort = (arr) => {
  if (arr.length <= 1) return arr;
  let left = [];
  let right = [];
  let pivotIndex = Math.floor(arr.length / 2);
  let pivotValue = arr.splice(pivotIndex, 1)[0];
  a.map((x) => (x > pivotValue ? right.push(x) : left.push(x)));
  // a.forEach((a,x) => (x > pivotValue ? right.push(x) : left.push(x)));
  return quickSort(left).concat(pivotValue, quickSort(right));
};

快速排序

7 👜 堆排序 (Heap Sort)

堆排序 (Heapsort) 是指利用堆这种数据结构所设计的一种排序算法。堆积是一个近似完全二叉树的结构,并同时满足堆积的性质:即子结点的键值或索引总是小于 (或者大于) 它的父节点。

7.1 算法描述

  • 将初始待排序关键字序列 (R1,R2….Rn) 构建成大顶堆,此堆为初始的无序区;
  • 将堆顶元素 R[1] 与最后一个元素 R[n] 交换,此时得到新的无序区 (R1,R2,……Rn-1) 和新的有序区 (Rn), 且满足 R[1,2…n-1]<=R[n];
  • 由于交换后新的堆顶 R[1] 可能违反堆的性质,因此需要对当前无序区 (R1,R2,……Rn-1) 调整为新堆,然后再次将 R[1] 与无序区最后一个元素交换,得到新的无序区 (R1,R2….Rn-2) 和新的有序区 (Rn-1,Rn). 不断重复此过程直到有序区的元素个数为 n-1, 则整个排序过程完成。

7.2 动图演示

堆排序

7.3 代码实现

Sorts an array of numbers, using the heapsort algorithm.

  • Use recursion.
  • Use the spread operator (...) to clone the original array, arr.
  • Use closures to declare a variable, l, and a function heapify.
  • Use a for loop and Math.floor() in combination with heapify to create a max heap from the array.
  • Use a for loop to repeatedly narrow down the considered range, using heapify and swapping values as necessary in order to sort the cloned array.
const heapsort = (arr) => {
  const a = [...arr];
  let l = a.length;

  const heapify = (a, i) => {
    const left = 2 * i + 1;
    const right = 2 * i + 2;
    let max = i;
    if (left < l && a[left] > a[max]) max = left;
    if (right < l && a[right] > a[max]) max = right;
    if (max !== i) {
      [a[max], a[i]] = [a[i], a[max]];
      heapify(a, max);
    }
  };

  for (let i = Math.floor(l / 2); i >= 0; i -= 1) heapify(a, i);
  for (i = a.length - 1; i > 0; i--) {
    [a[0], a[i]] = [a[i], a[0]];
    l--;
    heapify(a, 0);
  }
  return a;
};

heapsort

8 👜 计数排序 (Counting Sort)

计数排序不是基于比较的排序算法,其核心在于将输入的数据值转化为键存储在额外开辟的数组空间中。作为一种线性时间复杂度的排序,计数排序要求输入的数据必须是有确定范围的整数。

8.1 算法描述

  • 找出待排序的数组中最大和最小的元素;
  • 统计数组中每个值为 i 的元素出现的次数,存入数组 C 的第 i 项;
  • 对所有的计数累加 (从 C 中的第一个元素开始,每一项和前一项相加);
  • 反向填充目标数组:将每个元素 i 放在新数组的第 C(i) 项,每放一个元素就将 C(i) 减去 1.

8.2 动图演示

计数排序

8.3 代码实现

function countingSort(arr, maxValue) {
  var bucket = new Array(maxValue + 1),
    sortedIndex = 0;
  (arrLen = arr.length), (bucketLen = maxValue + 1);
  for (var i = 0; i < arrLen; i++) {
    if (!bucket[arr[i]]) {
      bucket[arr[i]] = 0;
    }
    bucket[arr[i]]++;
  }

  for (var j = 0; j < bucketLen; j++) {
    while (bucket[j] > 0) {
      arr[sortedIndex++] = j;
      bucket[j]--;
    }
  }
  return arr;
}

8.4 算法分析

计数排序是一个稳定的排序算法。当输入的元素是 n 个 0 到 k 之间的整数时,时间复杂度是 O(n+k), 空间复杂度也是 O(n+k), 其排序速度快于任何比较排序算法。当 k 不是很大并且序列比较集中时,计数排序是一个很有效的排序算法。

9 👜 桶排序 (Bucket Sort)

桶排序是计数排序的升级版。它利用了函数的映射关系,高效与否的关键就在于这个映射函数的确定。桶排序 (Bucket sort) 的工作的原理:假设输入数据服从均匀分布,将数据分到有限数量的桶里,每个桶再分别排序 (有可能再使用别的排序算法或是以递归方式继续使用桶排序进行排).

9.1 算法描述

  • 设置一个定量的数组当作空桶;
  • 遍历输入数据,并且把数据一个一个放到对应的桶里去;
  • 对每个不是空的桶进行排序;
  • 从不是空的桶里把排好序的数据拼接起来。

9.2 图片演示

桶排序

9.3 代码实现

Sorts an array of numbers, using the bucket sort algorithm.

  • Use Math.min(), Math.max() and the spread operator (...) to find the minimum and maximum values of the given array.
  • Use Array.from() and Math.floor() to create the appropriate number of buckets (empty arrays).
  • Use Array.prototype.forEach() to populate each bucket with the appropriate elements from the array.
  • Use Array.prototype.reduce(), the spread operator (...) and Array.prototype.sort() to sort each bucket and append it to the result.
const bucketSort = (arr, size = 5) => {
  const min = Math.min(...arr);
  const max = Math.max(...arr);
  const buckets = Array.from({ length: Math.floor((max - min) / size) + 1 }, () => []);
  arr.forEach((val) => {
    buckets[Math.floor((val - min) / size)].push(val);
  });
  return buckets.reduce((acc, b) => [...acc, ...b.sort((a, b) => a - b)], []);
};

bucketSort

9.4 算法分析

桶排序最好情况下使用线性时间 O(n), 桶排序的时间复杂度,取决与对各个桶之间数据进行排序的时间复杂度,因为其它部分的时间复杂度都为 O(n). 很显然,桶划分的越小,各个桶之间的数据越少,排序所用的时间也会越少。但相应的空间消耗就会增大。

10 👜 基数排序 (Radix Sort)

基数排序是按照低位先排序,然后收集;再按照高位排序,然后再收集;依次类推,直到最高位。有时候有些属性是有优先级顺序的,先按低优先级排序,再按高优先级排序。最后的次序就是高优先级高的在前,高优先级相同的低优先级高的在前。

10.1 算法描述

  • 取得数组中的最大数,并取得位数;
  • arr 为原始数组,从最低位开始取每个位组成 radix 数组;
  • 对 radix 进行计数排序 (利用计数排序适用于小范围数的特点);

10.2 动图演示

基数排序

10.3 代码实现

// LSD Radix Sort
function radixSort(arr, maxDigit) {
  var counter = [];
  var mod = 10;
  var dev = 1;
  for (var i = 0; i < maxDigit; i++, dev *= 10, mod *= 10) {
    for (var j = 0; j < arr.length; j++) {
      var bucket = parseInt((arr[j] % mod) / dev);
      if (counter[bucket] == null) {
        counter[bucket] = [];
      }
      counter[bucket].push(arr[j]);
    }
    var pos = 0;
    for (var j = 0; j < counter.length; j++) {
      var value = null;
      if (counter[j] != null) {
        while ((value = counter[j].shift()) != null) {
          arr[pos++] = value;
        }
      }
    }
  }
  return arr;
}

10.4 算法分析

基数排序基于分别排序,分别收集,所以是稳定的。但基数排序的性能比桶排序要略差,每一次关键字的桶分配都需要 O(n) 的时间复杂度,而且分配之后得到新的关键字序列又需要 O(n) 的时间复杂度。假如待排数据可以分为 d 个关键字,则基数排序的时间复杂度将是 O(d*2n) , 当然 d 要远远小于 n, 因此基本上还是线性级别的。

基数排序的空间复杂度为 O(n+k), 其中 k 为桶的数量。一般来说 n>>k, 因此额外空间需要大概 n 个左右。

参考链接

十大经典排序算法(动图演示)


文章作者: 庄引
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 庄引 !
  目录