Skip to content

Commit b872ea8

Browse files
author
polun
committed
add insertion sort
1 parent 2efdead commit b872ea8

File tree

4 files changed

+29
-2
lines changed

4 files changed

+29
-2
lines changed

code/bubbleSort.js renamed to code/01.bubbleSort.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ function bubbleSort(arr) {
1212
}
1313
}
1414
}
15+
16+
return arr;
1517
}
1618

1719
util(bubbleSort);

code/selectionSort.js renamed to code/02.selectionSort.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ function selectionSort(arr) {
1616
arr[length - i - 1] = arr[flag];
1717
arr[flag] = temp;
1818
}
19+
20+
return arr;
1921
}
2022

2123
util(selectionSort);

code/03.insertionSort.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
const util = require('./util.js');
2+
3+
function insertionSort(arr) {
4+
const length = arr.length;
5+
6+
let prefixIndex,
7+
current;
8+
9+
for (let i = 1; i < length; i++) {
10+
prefixIndex = i - 1;
11+
current = arr[i];
12+
while (prefixIndex >= 0 && arr[prefixIndex] > current) {
13+
arr[prefixIndex + 1] = arr[prefixIndex];
14+
15+
prefixIndex--;
16+
}
17+
18+
arr[prefixIndex + 1] = current;
19+
}
20+
21+
return arr;
22+
}
23+
24+
util(insertionSort);

code/util.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,5 @@ module.exports = function (sort) {
77
console.log(arr);
88
console.log('*'.repeat(20) + os.EOL);
99

10-
sort(arr);
11-
console.log(arr);
10+
console.log(sort(arr));
1211
};

0 commit comments

Comments
 (0)