Javascript Array insertionSort() method

Description

Javascript Array insertionSort() method


Array.prototype.insertionSort = function () {
    for (var i = 1; i < this.length; i++) {
        var value = this[i],
            j = i - 1;/*from www.j  av  a2 s  .  c  o  m*/
        while (j >= 0 && this[j] > value) {
            var temp = this[j];
            this[j] = this[j + 1];
            this[j + 1] = temp;
            j--;
        }
        this[j + 1] = value;
    }
    return this;
};

Javascript Array insertionSort()

Array.prototype.insertionSort = function(){
  if(this.length < 2){
    return this;/*from  w w  w .  j  ava2  s. c o m*/
  }
  for(var i=0; i<this.length; i++){
    var j = i;
    while(j > 0 && this[j] < this[j-1]){
      var jValue = this[j];
      this[j] = this[j-1];
      this[j-1] = jValue;
      j -= 1;
    }
  }
  return this;
}

var aList = [8, 3, 5, 1, 3, 9, 7];
aList.insertionSort();
console.log(aList);

Javascript Array insertionSort()

'use strict';//from w  w w.  ja  va 2s .co m

// ArraySorting
const ArraySorting = {};

ArraySorting.insertionSort = a => {
    for(let o = 1; o < a.length; o++) {
        for(let i = o; i > 0 && a[i] < a[i-1]; i--) {
            [a[i], a[i-1]] = [a[i-1], a[i]]
        }
        // Invariant: a[:o] is sorted
    }
}

Array.prototype.insertionSort = function () {
    ArraySorting.insertionSort(this);
}

exports.ArraySorting = ArraySorting;

Javascript Array insertionSort()

/**//from   ww  w .  j  a v a  2  s  .  c o m
 * Insertion Sort Javascript implementation
 *  - Best: n / Average: n^2 / Worst: n^2
 *  - Memory: 1 / Stable
 *
 * @author: Sebastian Kim
 */

Array.prototype.insertionSort = function() {
  for(var i = 1; i < this.length; i++) {
    var hole = i;
    while (hole > 0 && this[hole - 1] > this[i]) {
      hole--;
    }
    this.splice(hole, 0, this[i]);
    this.splice(i + 1, 1);
  }

  return this;
}

Javascript Array insertionSort()

Array.prototype.insertionSort = function () {
    var n = this.length,
        i,// www  .  ja  v a  2 s.  c  o m
        j,
        swap;
        
    for (i = 0; i < n; ++i) {
        swap = this[i];
        j = i;
        while (j > 0 && this[j-1] > swap) {
            this[j] = this[j-1];
            --j;
        }
        this[j] = swap;
    }
    
};

var data = [6,5,1,8,3,7,2,9,4];
 
 data.insertionSort();
 
 console.log(data);

Javascript Array insertionSort()

/*/*from ww w .  ja  v a 2s  . c o m*/
 *Adds a method into array object that sorts the array via
 *insertion sort in increasing order
 *Algorithm Complexity: O(n^2)
 *
 *@param: array 
 *@return: sorted array
 *@author: ketanSaxena
*/
Array.prototype.insertionSort = function() {
  var index, innerIndex, LENGTH = this.length;
  for(index = 0; index < LENGTH; index++) {
    var position, valueToInsert = this[index];
    for (position = index; position > 0 && this[position -1] > valueToInsert; position--) {
      this[position] = this[position - 1];
    }

    if(position != index) {
      this[position] = valueToInsert;
    }
  }

  return this;
}

Javascript Array insertionSort()

Array.prototype.insertionSort = function(){
    /*  w w  w.ja v a  2  s .c o m*/
    if(this.length === 0)
        return "Array is empty!!";
    else if(this.length ===1)
        return this;
    else{
        
        for(var outerLoopIndex =1,arrLen = this.length;
            outerLoopIndex<arrLen;outerLoopIndex++)
        {
            
            var temp = this[outerLoopIndex];
            for(var innerLoopIndex = outerLoopIndex-1;
                innerLoopIndex >= 0 && this[innerLoopIndex] > temp ;innerLoopIndex--)
            {
                this[innerLoopIndex+1] = this[innerLoopIndex];   
             
            }
            this[innerLoopIndex+1] = temp;
           
        }
    }
    return this;
}

Javascript Array insertionSort()

"use strict";//from w w  w  .  ja v a  2  s  .  co  m

/** 
 * Insertion sort
 */
Array.prototype.insertionSort = function() {
  // iterate from key 1 (not 0) to length - 1
  // compare with previous value, and swap until no swap
  // increment key
  for (var key = 1; key < this.length; key++) {
    // A bit strange to see this type of logic in a for-loop, but it
    // makes sense
    for (var swap_key = key; this[swap_key] < this[swap_key - 1]; swap_key--) {
      var temp = this[swap_key];
      this[swap_key] = this[swap_key - 1];
      this[swap_key - 1] = temp;
    }
  }
};

/**
 * Helper function 
 */
var assert = function(expression, name) {
  if ( ! expression) {
    console.log('** Assertion failed', name || '')
  }
}


/**
 * Tests
 */


var a1 = [5,4,3,6,7,1,2,8,9];
a1.insertionSort();
console.log(a1);
// Use toString() to compare arrays 
assert(a1.toString() === [1,2,3,4,5,6,7,8,9].toString(), 'Test it is sorted');

Javascript Array insertionSort()

// insertionSort (mutates current array)
Array.prototype.insertionSort = (function() {

  const insert = (that, rightIndex, value) => {
    // TODO: What is the best way to make thie insertion sort algorithm not mutate the
    // original array?

    let i;//w w  w  . j a  v  a2 s  .c o  m
    for(i=rightIndex; i > -1 && that[i] > value; i--) {
        that[i + 1] = that[i];
    }

    that[i+1] = value;
  };

  return function() {
    let that = this;

    console.log(that.length);
    for(let i = 1; i < that.length; i++) {
      console.log(`insert(${i-i}, ${that[i]})`);
      insert(that, i-1, that[i]);
    }
  };
}());

// test
let al = [9,8,7,6,5,4,3,2,1,0].insertionSort();

console.assert(
  al[0] === 0,
  al[1] === 1,
  al[2] === 2,
  al[3] === 3,
  al[4] === 4,
  al[5] === 5,
  al[6] === 6,
  al[7] === 7,
  al[8] === 8,
  al[9] === 9
);

Javascript Array insertionSort()

// Patched on the Array Prototype
Array.prototype.insertionSort = function () {
  console.time('InsertionSort')
  var arr = this/*from  ww  w  . j  av a2 s.c o  m*/
  // loop through each element in our array
  for (let i = 1; i < arr.length; ++i) {
    let j = i
    // loop backwards and shuffle the content of the array, rather than creating a new
    while (j > 0 && arr[j] < arr[j - 1]) {
      let temp = arr[j]
      arr[j] = arr[j - 1]
      arr[j - 1] = temp
      --j
    }
  }
  console.timeEnd('InsertionSort')
}

let arr = []
let max = 100000
for (let i = 0; i < max; ++i) {
  arr.push(Math.round(Math.random() * 10))
}
console.log('sorting array of length: ', max)
// console.log('unsorted array: ', arr)
arr.insertionSort()
// console.log('sorted array: ', arr)
// console.log('restorting array...')
arr.insertionSort()



PreviousNext

Related