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(len <= 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);