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]));

 

posted @ 2019-01-03 16:05  shangyueyue  阅读(148)  评论(0编辑  收藏  举报