- function quicksort(arr) {
- if (arr.length == 0)
- return arr;
- var first = arr[0];
- var smaller = [], bigger = [];
- for ( var i = 1; i < arr.length; i++) {
- if (arr[i] < first)
- smaller.push(arr[i]);
- else
- bigger.push(arr[i]);
- }
- return Array.prototype.concat(quicksort(smaller), [ first ],quicksort(bigger));
- }
- function quicksorttow(a,p,q){
- if( a && a.length>1 &&p<q){
- var r=partition(a,p,q);
- quicksorttow(a,p,r-1);
- quicksorttow(a,r+1,q);
- }
- return a;
- }
- function partition(a,p,q){
- if(a && a.length>1){
- var x=a[q];
- var i=p-1;
- var j=p;
- for(;j<q;j++){
- if(a[j]<x){
- i++;
- var t=a[j];
- a[j]=a[i];
- a[i]=t;
- }
- }
- a[q]=a[i+1];
- a[i+1]=x;
- return i+1;
- }
- }
- function createArr(len){
- var arr=[];
- for(var i=len;i>=0;i--){
- arr.push(i);
- }
- return arr;
- }
- var len=10000;
- var arr=createArr(len);
- console.time("quicksort");
- console.log(quicksort(arr));
- console.timeEnd("quicksort");
- console.time("quicksorttwo");
- console.log(quicksorttow(arr,0,arr.length-1));
- console.timeEnd("quicksorttwo");
- console.time("js_sort");
- console.log( arr.sort());
- console.timeEnd("js_sort");
- //该片段来自于http://www.codesnippet.cn/detail/0602201511744.html
来源: http://www.codesnippet.cn/detail/0602201511744.html