Home > Web Front-end > JS Tutorial > 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
Release: 2016-05-16 16:36:25
Original
1274 people have browsed it

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));//递归
}
Copy after login
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template