Javascript Array selectSort()

Description

Javascript Array selectSort()


Array.prototype.selectSort = function(){
 var len = this.length, i, j, k, tmp;
 for(i = 0; i < len; i++){
  k = i;//from  w w  w .j  ava  2s  .  co  m
  for(j = i + 1; j < len; j++){
   if(this[j] < this[k])
    k = j;
  }
  if(k != i){
   tmp = this[k];
   this[k] = this[i];
   this[i] = tmp;
  }
 }
 return this;
}

var arr = [14, 6, 9, 4, 11];
var nArr = arr.selectSort(0,4);
console.log(nArr);

Javascript Array selectSort()

Array.prototype.selectSort = function() {
 for(var i = 0; i <= this.length - 2; i++) {
  var index = i;/*from  www  .  j  a v a 2  s.  co m*/
  for(var z = i + 1; z <= this.length - 1; z++) {
   if(this[z] < this[index]) {
    index = z;
   }
  }
  if(index != i) {
   var temp = this[i];
   this[i] = this[index];
   this[index] = temp;
  }
 }
 return this;
}

var a = [23,34,24,56,67,98,14,28,39];
console.log(a.length);
a.selectSort();
console.log(a);



PreviousNext

Related