forked from trekhleb/javascript-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BubbleSort.js
38 lines (30 loc) · 1.01 KB
/
BubbleSort.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
import Sort from '../Sort';
export default class BubbleSort extends Sort {
sort(originalArray) {
// Flag that holds info about whether the swap has occur or not.
let swapped = false;
// Clone original array to prevent its modification.
const array = [...originalArray];
for (let i = 1; i < array.length; i += 1) {
swapped = false;
// Call visiting callback.
this.callbacks.visitingCallback(array[i]);
for (let j = 0; j < array.length - i; j += 1) {
// Call visiting callback.
this.callbacks.visitingCallback(array[j]);
// Swap elements if they are in wrong order.
if (this.comparator.lessThan(array[j + 1], array[j])) {
[array[j], array[j + 1]] = [array[j + 1], array[j]];
// Register the swap.
swapped = true;
}
}
// If there were no swaps then array is already sorted and there is
// no need to proceed.
if (!swapped) {
return array;
}
}
return array;
}
}