码迷,mamicode.com
首页 > 编程语言 > 详细

数组排序

时间:2015-07-14 00:03:05      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

1.冒泡排序

 1  Array.prototype.specialSort = function(){
 2       //冒泡排序
 3       var len = this.length,
 4           a = 0;
 5       for(var i = 0; i < len; i++){
 6           for(var j =0; j < len-1; j++){
 7               if(this[j]>this[j+1]){
 8                   a = this[j];
 9                   this[j] = this[j+1];
10                   this[j+1] = a;
11               }
12           }
13       }
14       return this;
15   };
16   
17   var newArr = [2,4,2,1,6].specialSort();
18   console.log(newArr); //[1,2,2,4,6]

2.快速排序

 1   Array.prototype.quickSort = function(){
 2       var len = this.length;
 3       if(this.length <= 1){
 4           return this;
 5       }
 6       
 7       var pivot = this.shift();  //基准元素
 8       var left = [];
 9       var right = [];
10       
11       for(var i = 0; i < len-1; i++){
12           if(this[i] < pivot){   //小于基准元素的放在左边
13               left.push(this[i]);
14           }else{
15               right.push(this[i]);   //大于基准元素的放在右边
16           }
17       }
18       return left.quickSort().concat([pivot], right.quickSort());
19   };
20   
21   var newArr = [2,4,6,1,3].quickSort();  //[1, 2, 3, 4, 6]
22   console.log(newArr);

 

数组排序

标签:

原文地址:http://www.cnblogs.com/webliu/p/4644120.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!