计数排序&快速排序

111 阅读1分钟

计数排序

全靠脑袋想的有益尝试

let countSort = (arr) => {
  let max = 0;
  let hashTable = {};
  for (i = 0; i < arr.length; i++) {
    if (arr[i] in hashTable) {
      hashTable[arr[i]] += 1;
    } else {
      hashTable[arr[i]] = 1;
    }
    if (arr[i] > max) {
      max = arr[i];
    }
  }
  let result = [];
  for (i = 0; i <= max; i++) {
    if (hashTable[i]) {
      for (let index = 0; index < hashTable[i]; index++) {
        result.push(i);
      }
    }
  }
  return result;
};
console.log(countSort([3, 5, 7, 7, 6, 0]));

快速排序

写过框架,画过思路,手写了代码,稍微熟练之后的宝贵留档

let quickSort = (arr) => {
  if (arr.length <= 1) {
    return arr;
  }
  let pivotIndex = Math.floor(arr.length / 2);
  let pivot = arr.splice(pivotIndex, 1)[0];
  let left = [];
  let right = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] < pivot) {
      left.push(arr[i]);
    } else {
      right.push(arr[i]);
    }
  }
  return quickSort(left).concat([pivot], quickSort(right));
};
console.log(quickSort([1, 2, 3, 5, 5, 4, 9, 7, 60]));