forked from Ren0503/javascript-algorithms-and-data-structure
-
Notifications
You must be signed in to change notification settings - Fork 8
/
InsertionSort.js
39 lines (32 loc) · 1.25 KB
/
InsertionSort.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import Sort from '../Sort';
export default class InsertionSort extends Sort {
sort(originalArray) {
const array = [...originalArray];
// Đi qua tất cả phần tử của mảng...
for (let i = 1; i < array.length; i += 1) {
let currentIndex = i;
// Gọi hàm callback.
this.callbacks.visitingCallback(array[i]);
// Kiểm tra xem phần tử trước đó có lớn hơn phần tử hiện tại hay không.
// Nếu có, hãy hoán đổi hai phần tử.
while (
array[currentIndex - 1] !== undefined
&& this.comparator.lessThan(array[currentIndex], array[currentIndex - 1])
) {
// Gọi hàm callback.
this.callbacks.visitingCallback(array[currentIndex - 1]);
// Hoán đổi phần tử.
[
array[currentIndex - 1],
array[currentIndex],
] = [
array[currentIndex],
array[currentIndex - 1],
];
// Chuyển sang chỉ mục bên trái.
currentIndex -= 1;
}
}
return array;
}
}