Home > Web Front-end > JS Tutorial > body text

How to implement quick sort

一个新手
Release: 2017-09-26 15:06:09
Original
1263 people have browsed it

Quick sort requires:

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

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]));
Copy after login

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!

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