闲着没事——写几个js排序算法

/**
  * Array BubleSort
  */
 Array.prototype.bubleSort = function (){
  var length = this.length;
  for(var i=0; i<length; i++) {
   for(var j=0; j<length-i-1; j++) {
    if (this[j] > this[j+1]) {
     var tmp = this[j];
     this[j] = this[j+1];
     this[j+1] = tmp;
    }
   }
   console.log(this.toString());
  }
  return this;
 }
 
 /**
  * Array QuickSort
  */
 Array.prototype.quickSort = function (){  
  if (this.length <=0 ) return this;
  console.log(this.toString());
  var x = this[0];
  var l = new Array();
  var r = new Array();
  for(var i=1; i<this.length; i++ ) {
   if (this[i] > x) {
    r.push( this[i] );
   } else {
    l.push( this[i] );
   }
  }
  l = l.quickSort();
  r = r.quickSort();
  return l.concat(x,r);
 }
 /**
  * Array InsertSort
  */
 Array.prototype.insertSort = function () {  
  var j = 0;
  for(var i=1; i<this.length; i++ ) {
   j = i - 1;
   var tmp = this[i];
   while ( (j >= 0) &&  (this[j] > tmp) ) {
    this[j+1] = this[j];
    j--;
   }
   this[j+1] = tmp;
   console.log(this);
  }
  return this;
 }
 var arr = [9,32,1,3,2,324,52,4,10];
 console.log('-------------QuickSort--------------');
 console.log(arr.quickSort());
 console.log('-------------InsertSort--------------');
 console.log(arr.insertSort()); 
 console.log('-------------BubleSort--------------');

 console.log(arr.bubleSort());


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值