Javascript Array insertSort() method

Description

Javascript Array insertSort() method


Array.prototype.insertSort = function () {
 var len = this.length;
 var i, j, tmp;/*  w ww. ja va  2s  .  c  o  m*/
 for (i = 1; i < len; i++) {
  tmp = this[i];
  j = i - 1;
  while (j > 0 && tmp < this[j]) {
   //console.log('j',this[j])
   this[j + 1] = this[j];
   j--;
  }
  this[j + 1] = tmp;
 }
 return this;
}

var arr = [1, 6, 9, 4, 11];
var nArr = arr.insertSort();
console.log(nArr);

Javascript Array insertSort()

Array.prototype.insertSort = function () {
    'use strict';

    var lastIndex = this.length,
        temp,/*from w w  w. j  a  v  a  2 s .  c  o m*/
        i,
        j;

    for ( i = 1 ; i < lastIndex ; i++ ) {

        for( j = 0 ; j < i ; j++ ){
            
            if( this[i] < this[j] ){
                temp = this[i];
                this[i] = this[j];
                this[j] = temp;
            }

        }   

    }

    return this;
};

var vector = [50,6, 2, 5, 23, 9, 17, 29, 3];

console.log(vector);

console.log(vector.insertSort());

Javascript Array insertSort()

Array.prototype.insertSort = function() {
 for(var i = 1; i < this.length; i++) {
  var temp = this[i];
  var inp = i;// w w w . j  a  va2  s. c  o  m
  while(inp > 0 && temp < this[inp - 1]){
   this[inp] = this[inp - 1];
   inp--;
  }
  this[inp] = temp;
 }
 return this;
}

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



PreviousNext

Related