Words etch cherished moments.
OG

JS常见排序算法

2,035 words, 5 min read
2019/12/17 PM
257 views

#JS常见排序算法

#冒泡排序

冒泡排序算法比较简单,它重复地走访过要排序的数列,一次比较两个元素,如果它们的顺序错了,就将它们交换过来。

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
function bubbleSort(arr) { const len = arr.length; for (let i = 0; i < len - 1; i++) { for (let j = 0; j < len - i - 1; j++) { if (arr[j] > arr[j + 1]) { [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]; } } } return arr; }

#选择排序

选择排序算法首先在未排序的序列中找到最小(大)元素,存放到排序序列的起始位置,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
function 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; }

#插入排序

插入排序算法将数组拆分为较小的序列,对每个序列进行排序,最终合并为一个有序数组。它通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,并在必要时移动元素,以使得插入的元素能够挤进有序序列中合适的位置。

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
function 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; }

#快速排序

快速排序是一种采用分治思想的排序算法,它首先选取一个基准值(pivot),然后将数组划分为两部分:小于基准值的部分和大于基准值的部分。不断重复这个过程直到所有子数组只剩下一个元素,即完成了排序。

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
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)]; }
Creative Commons BY-NC 4.0
https://zhangwurui.cn/article/68
0/0comments
Guest
Start the discussion...
Be the first to comment