Skip to content

Instantly share code, notes, and snippets.

@thinkphp
Created January 19, 2012 19:29
Show Gist options
  • Select an option

  • Save thinkphp/1641985 to your computer and use it in GitHub Desktop.

Select an option

Save thinkphp/1641985 to your computer and use it in GitHub Desktop.
Insertion Sort in JavaScript
/*
Insertion Sort in JavaScript
Twitter : http://twitter.com/thinkphp
Website : http://thinkphp.ro
Google Plus : http://gplus.to/thinkphp
MIT Style License
*/
function insertionSort(arr) {
var n = arr.length-1,
temp;
for(var i=1;i<n;i++) {
temp = arr[i];
j = i - 1;
while(j>=0 && arr[j] > temp) {
arr[j+1] = arr[j]
j--
}
arr[j+1] = temp
}
return arr
}
function insertionSort2(arr) {
var n = arr.length,
temp;
for(var i=1;i<n;i++) {
temp = arr[i];
for(var j=i-1;j>=0;j--) {
if(arr[j] > temp) {
arr[j+1] = arr[j]
} else {
break
}
}
arr[j+1] = temp
}
return arr
}
function insertionSortModified(arr) {
var n = arr.length,
temp,
li,
ls;
for(var i=1;i<n;i++) {
temp = arr[i]
li = 0;
ls = i-1
while(li<=ls) {
middle = parseInt((li+ls)/2);
if(temp < arr[middle]) {
ls = middle - 1
} else {
li = middle + 1
}
}
for(var j=i-1;j>=li;j--) {
arr[j+1] = arr[j]
}
arr[li] = temp
}
return arr
}
var arr = [9,8,7,6,5,4,3,2,1,0]
console.log(insertionSortModified(arr))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment