-
Notifications
You must be signed in to change notification settings - Fork 497
/
Copy pathbubble-sort-counters.js
64 lines (55 loc) · 1.95 KB
/
bubble-sort-counters.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// sample of arrays to sort
var arrayRandom = [9, 2, 5, 6, 4, 3, 7, 10, 1, 8];
var arrayOrdered = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var arrayReversed = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
// swap function helper
function swap(array, i, j) {
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
// be careful: this is a very basic implementation which is nice to understand the deep principle of bubble sort (going through all comparisons) but it can be greatly improved for performances
function bubbleSortBasic(array) {
var countOuter = 0;
var countInner = 0;
var countSwap = 0;
for(var i = 0; i < array.length; i++) {
countOuter++;
for(var j = 1; j < array.length; j++) {
countInner++;
if(array[j - 1] > array[j]) {
countSwap++;
swap(array, j - 1, j);
}
}
}
console.log('outer:', countOuter, 'inner:', countInner, 'swap:', countSwap);
return array;
}
bubbleSortBasic(arrayRandom.slice()); // => outer: 10 inner: 90 swap: 21
bubbleSortBasic(arrayOrdered.slice()); // => outer: 10 inner: 90 swap: 0
bubbleSortBasic(arrayReversed.slice()); // => outer: 10 inner: 90 swap: 45
// correct implementation: this is the usual implementation of the bubble sort algorithm. Some loops execution are avoided if not they are not needed
function bubbleSort(array) {
var countOuter = 0;
var countInner = 0;
var countSwap = 0;
var swapped;
do {
countOuter++;
swapped = false;
for(var i = 0; i < array.length; i++) {
countInner++;
if(array[i] && array[i + 1] && array[i] > array[i + 1]) {
countSwap++;
swap(array, i, i + 1);
swapped = true;
}
}
} while(swapped);
console.log('outer:', countOuter, 'inner:', countInner, 'swap:', countSwap);
return array;
}
bubbleSort(arrayRandom.slice()); // => outer: 9 inner: 90 swap: 21
bubbleSort(arrayOrdered.slice()); // => outer: 1 inner: 10 swap: 0
bubbleSort(arrayReversed.slice()); // => outer: 10 inner: 100 swap: 45