当前位置:网站首页>JS quick sort

JS quick sort

2022-06-12 18:02:00 Out of the autistic bird

Quick sort

/** *  obtain midValue Two ways  *  Use splice, The original array will be modified  *  Use slice, The original array will not be modified  * O(n*logn) *  Compare them separately splice and slice,slice Much faster  */

function quickSort(arr){
    
  const length = arr.length
  if(length === 0) return arr

  const midIndex = Math.floor(length/2)
  // splice Modify the original array , Returns an array of deleted elements 
  const midValue = arr.splice(midIndex,1)[0]

  const left = []
  const right = []

  //  Be careful : You can't use it directly here length, It's about using arr.length, because arr Has been splice modify 
  for(let i=0;i<arr.length;i++){
    
    if(arr[i]<midValue){
    
      //  Less than left 
      left.push(arr[i])
    }else{
    
      // Larger than on the right 
      right.push(arr[i])
    }
  }
  return quickSort(left).concat([midValue],quickSort(right))
}

const arr = [1,6,2,7,8,5,3]
console.log(quickSort(arr));
原网站

版权声明
本文为[Out of the autistic bird]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206121758171257.html