24、快速排序

找到数组中的中间项,然后将其从原来数组中移除,并且获取这个中间项值。依次拿数组中的每项跟中间项进行对比,小的放左边大的放右边

 let ary = [23,31,4,7,3,9]

function quick(ary){
  if(ary.length<=1){return ary}
  let middleIndex = Math.floor(ary.length/2)
  let middleVal = ary.splice(middleIndex,1)[0]
  let leftary = [],
          rightary = []
  for(let i = 0;i<ary.length;i++){
      ary[i]<middleVal?leftary.push(ary[i]):rightary.push(ary[i])

  }
  return (quick(leftary)).concat(middleVal,quick(rightary))
}

results matching ""

    No results matching ""