• js排序


    我的github

    https://github.com/shangyueyue/ssy-utils/tree/master/src/arithmetic/sort

    一、冒泡排序

    // 冒泡排序
    function bubbleSort(arr) {
      const _arr = [...arr];
      for (let i = 1; i < _arr.length - 1; i++) {
        for (let j = 0; j < _arr.length - i; j++) {
          if (_arr[j] > _arr[j + 1]) {
            [_arr[j + 1], _arr[j]] = [_arr[j], _arr[j + 1]];
          }
        }
      }
      return _arr;
    }
    
    const arr = [6, 2, 8, 4, 3, 5, 3];
    console.log(bubbleSort(arr));

    二、插入排序

    // 插入法排序
    function insertSort(arr) {
      if (!Array.isArray(arr)) throw new Error('arr must be a Array');
      const $arr = [...arr];
      for (let i = 1; i < $arr.length; i++) {
        const temp = $arr[i];
        let j = i - 1;
        while (j >= 0 && temp < $arr[j]) {
          $arr[j + 1] = $arr[j];
          j--;
        }
      }
    }
    const arr = [6, 2, 8, 4, 3, 5, 3];
    insertSort(arr);

    三、快速排序

    // 快速排序
    
    function quickSort(arr) {
      if (!Array.isArray(arr)) {
        throw new Error('param must be Array');
      }
      if (arr.length <= 1) return arr;
      const middleIndex = Math.floor(arr.length / 2);
      const middleArr = arr.splice(middleIndex, 1);
      const leftArr = [];
      const rightArr = [];
      for (let i = 0; i < arr.length; i++) { // eslint-disable-line
        if (arr[i] <= middleArr[0]) {
          leftArr.push(arr[i]);
        } else {
          rightArr.push(arr[i]);
        }
      }
      return [...quickSort(leftArr), ...middleArr, ...quickSort(rightArr)];
    }
    
    const result = quickSort([2, 1, 4, 2, 5, 3]);
    console.log(result);

     四、归并排序

    // // 归并排序
    function merge(left, right) {
      const result = [];
      while (left[0] && right[0]) {
        if (left[0] < right[0]) {
          result.push(left.shift());
        } else {
          result.push(right.shift());
        }
      }
      return result.concat(left, right);
    }
    function mergeSort(arr) {
      if (arr.length <= 1) return arr;
      const middleIndex = Math.floor(arr.length / 2);
      const left = arr.slice(0, middleIndex);
      const right = arr.slice(middleIndex);
      return merge(mergeSort(left), mergeSort(right));
    }
    
    console.log(mergeSort([8, 4, 3, 6, 2, 4, 2, 5, 3]));

     

  • 相关阅读:
    异或交换真的比开一个tmp快吗?
    淘宝前端团队的干货《论版本号的正确打开方式》
    箭头函数
    js对象引用问题
    json+underscore+Node 小例子
    fs.stat()
    Express static静态路由
    剑指offer(二) 替换空格
    Node实现简单的表单+图片上传+路由
    剑指offer(一) 二维数组的查找
  • 原文地址:https://www.cnblogs.com/shangyueyue/p/10214757.html
Copyright © 2020-2023  润新知