js+排序

快排

const quicksort = (arr) => {
  if(arr.length <= 1) return arr
  let pivot = arr[0]
  let left = arr.slice(1).filter((ele) => ele < pivot)
  let right = arr.slice(1).filter((ele) => ele > pivot)
  return quicksort(left).concat([pivot]).concat(quicksort(right))
}

归并排序

const mergesort = (arr) => {
  if (arr.length <= 1) return arr
  let left = mergesort(arr.slice(0,arr.length / 2))
  let right = mergesort(arr.slice(arr.length/2))
  return merge(left, right)
}

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

你可能感兴趣的:(js+排序)