冒泡排序

  • 原地排序
  • 稳定排序
  • 时间复杂度:O(n^2)

    1. function dubbleSort (arr) {
    2. for(let i = 0; i < arr.length; i++) {
    3. let flag = false;
    4. for(let j = 0; j < arr.length - i - 1; j++) {
    5. if (arr[j] > arr[j+1]) {
    6. const temp = arr[j+1];
    7. arr[j+1] = arr[j];
    8. arr[j] = temp;
    9. flag = true;
    10. }
    11. }
    12. if (!flag) break;
    13. }
    14. return arr;
    15. }

    选择排序

  • 原定排序

  • 不稳定排序
  • 时间复杂度:O(n^2)

    1. function selectionSort (arr) {
    2. let minIndex = 0;
    3. for(let i = 0; i < arr.length; i++) {
    4. minIndex = i;
    5. for(let j = i + 1; j < arr.length; j++) {
    6. if (arr[j] < arr[minIndex]) {
    7. minIndex = j;
    8. }
    9. }
    10. const temp = arr[minIndex];
    11. arr[minIndex] = arr[i];
    12. arr[i] = temp;
    13. }
    14. return arr;
    15. }

    插入排序

  • 原地排序

  • 稳定排序
  • 时间复杂度:O(n^2)

    1. function insertionSort (arr) {
    2. for(let i = 1; i < arr.length; i++) {
    3. let value = a[i];
    4. let j = i - 1;
    5. for(; j >= 0; j--) {
    6. if (a[j] > value) {
    7. a[j+1] = a[j];
    8. }
    9. }
    10. a[j+1] = value;
    11. }
    12. }

    归并排序

  • 非原地排序

  • 稳定排序
  • 时间复杂度:O(nlog(n)) ```javascript const mergeSort = function(arr) { if (arr.length < 2) return arr; const midIndex = Math.floor(arr.length / 2); const left = arr.slice(0, midIndex); const right = arr.slice(midIndex, arr.length); return merge(mergeSort(left), mergeSort(right)); }

const merge = function(left, right) { const res = []; while(left.length && right.length) { if (left[0] <= right[0]) { res.push(left.shift()); } else { res.push(right.shift()); } } while(left.length) res.push(left.shift()); while(right.length) res.push(right.shift()); return res }

  1. <a name="yGrXN"></a>
  2. ## 快速排序
  3. - 原地排序
  4. - 非稳定排序
  5. - 时间复杂度:O(nlog(n))
  6. ```javascript
  7. const quickSort = function(arr) {
  8. if (arr.length < 2) return arr;
  9. const midIndex = Math.floor(arr.length / 2);
  10. const mid = arr.splice(midIndex, 1)[0];
  11. const left = [];
  12. const right = [];
  13. for(let i = 0; i < arr.length; i++) {
  14. if (arr[i] < mid) {
  15. left.push(arr[i]);
  16. } else {
  17. right.push(arr[i]);
  18. }
  19. }
  20. return quickSort(left).concat([mid], quickSort(right));
  21. }