diff --git a/chapters/chapter-2-sorting/2.1-elementary-sorts/insertion.js b/chapters/chapter-2-sorting/2.1-elementary-sorts/insertion.js index 00a4874..5f7f1f0 100644 --- a/chapters/chapter-2-sorting/2.1-elementary-sorts/insertion.js +++ b/chapters/chapter-2-sorting/2.1-elementary-sorts/insertion.js @@ -8,11 +8,13 @@ console.log('> input: ' + input); // insertion function insertion(input) { for(var i = 1, len = input.length; i < len; i++) { - for(var j = i; j > 0; j--) { - if(input[j] < input[j - 1]) { - input[j] = [input[j - 1], input[j - 1] = input[j]][0]; - } + var insertion = input[i]; + var j = i; + while (j > 0 && insertion < input[j-1]) { + input[j] = input[j-1]; + j--; } + input[j] = insertion; } return input; }