Javascript Algorithm Array Sort Insertion Sort 3

Description

Javascript Algorithm Array Sort Insertion Sort 3

/**/*from  w ww.  ja  v a2 s .  com*/
 * Sort the a array using the insertion sort algorithm
 * @param  {Array} a 
 * @return {Array} sorted array
 */
function insertionSort(a){
  var l   = arr.length,
    i   = 0,
    j   = 0,
    key  = 0;

  for( j=1;j<l;j+=1 ){
    key  = a[j];
    i  = j-1;
    while( i>-1 && a[i]>key ){
      a[i+1] = a[i]
      i-=1;
    }
    a[i+1] = key;
  }

  return a;
}

var arr = [8,6,1,4,-1,4,99,-12,345,12,-1245,999,0];
arr = insertionSort(arr);
console.log( arr );



PreviousNext

Related