Home  >  Article  >  Web Front-end  >  JavaScript uses the push method of the array to complete quick sort_javascript skills

JavaScript uses the push method of the array to complete quick sort_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:36:251212browse

There are many methods of sorting. This section introduces the use of the push method of the array to complete quick sorting

function quickSort(arr){
 if(arr.length <= 1) return arr;//判断是否有效数组
 var cut = Math.floor(arr.length/2);//取中间下标
 var left = [],right = [];
 var num = arr.splice(cut,1)[0];//取基准值
 for(var i = 0;i < arr.length;i ++){
  if(arr[i] < num){
   left.push(arr[i]);//小的放左边
  }else {
   right.push(arr[i]);//大的放右边
  }
 }
 return quickSort(left).concat(num,quickSort(right));//递归
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn