<h1>Insertion sort algorithm in JavaScript</h1>
<p>Please check javascript code.</p>
/***************************************
* sort
***************************************/
var insertionSort = function(list){
var length = list.length,
i = 1,
k,
sortedIndex = 0,
target,
sorted;
for(; i < length; i++){
k = sortedIndex;
target = list[i];
sort: while(k >= 0){
sorted = list[k];
if(sorted < target){
list.splice(i,1);
list.splice(k+1,0,target);
break sort;
}
--k;
if(k < 0){
list.splice(i,1);
list.splice(0,0,target);
}
}
console.log('processing... ' + list);
++sortedIndex;
}
return list;
};
/***************************************
* main
***************************************/
var before = [0,9,3,4,6,7,8,2,1,5];
console.log('before : ' + before);
var after = insertionSort(before);
console.log('after : ' + after);
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.