简体   繁体   中英

JavaScript Algorithm Insertion Sort slightly off

Here is the link to my JavaScript Insertion Sort Algorithm

Quite simply, I just can't figure out why I can't get that pesky arr[0] to get sorted correctly. I've tried everything I know of. sigh

It's pretty close though.

Any idea's

 var aoo = [5,2,4,6,1,3]; function jInsertionSort(a) { for(var j=2; j<a.length; j++){ //console.log(j); var key = a[j]; var i = j - 1; while (i > 0 && a[i] > key) { a[i+1] = a[i]; i = i-1; } a[i+1]=key; } return a; } var aooSorted = jInsertionSort(aoo); console.log("jInsertionSort = ["+aooSorted+"]"); 

?

JavaScript Insertion Sort Algorithm

You almost got it, this works:

 var aoo = [5,2,4,6,1,3]; function jInsertionSort(a) { for(var j=1; j<a.length; j++){ var key = a[j]; var i = j; while (i > 0 && a[i-1] > key) { a[i] = a[i - 1]; a[i - 1] = key; i = i-1; } } return a; } var aooSorted = jInsertionSort(aoo); console.log("jInsertionSort = ["+aooSorted+"]"); 

 var aoo = [5,2,4,6,1,3]; function jInsertionSort (a) { for (var i = 0; i < a.length; i++) { var k = a[i]; for (var j = i; j > 0 && k < a[j - 1]; j--) a[j] = a[j - 1]; a[j] = k; } return a; } var aooSorted = jInsertionSort(aoo); console.log("jInsertionSort = ["+aooSorted+"]"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM