Home  >  Article  >  Web Front-end  >  How to implement quick sort

How to implement quick sort

一个新手
一个新手Original
2017-09-26 15:06:091243browse

Quick sort requires:

 //找一个基准点//建立两个数组,分别存储在左右两边的数组//利用递归处理左右两组;//将结果合并起来

Implementation code:

function quickSort(arr){
    if(arr.length<=1) return arr;    
    var num=Math.floor(arr.length/2);    
    var Value=arr.splice(num,1);    
    var left=[];    
    var right=[];    
    for(var i= 0,len=arr.length;i<len;i++){
        arr[i]<Value?left.push(arr[i]):right.push(arr[i]);
    }    return quickSort(left).concat(Value,quickSort(right))
}
console.log(quickSort([12, 5, 37,55,11,21 ,6, 22, 40]));

The above is the detailed content of How to implement quick sort. For more information, please follow other related articles on the PHP Chinese website!

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