Skip to content

Commit

Permalink
Update insertion.js
Browse files Browse the repository at this point in the history
修改插入排序实现方式,由原本的一个个交换改为先数组移位再插入正确的位置。
  • Loading branch information
StevenYuysy authored Aug 24, 2016
1 parent d0530da commit 974e82c
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions chapters/chapter-2-sorting/2.1-elementary-sorts/insertion.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down

0 comments on commit 974e82c

Please # to comment.