-
Notifications
You must be signed in to change notification settings - Fork 497
/
Copy pathselection-sort-counters.js
39 lines (34 loc) · 1002 Bytes
/
selection-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
// sample of arrays to sort
let arrayRandom = [9, 2, 5, 6, 4, 3, 7, 10, 1, 8];
let arrayOrdered = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let arrayReversed = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
// swap function helper
function swap(array, i, j) {
let temp = array[i];
array[i] = array[j];
array[j] = temp;
}
function selectionSort(array) {
let countOuter = 0;
let countInner = 0;
let countSwap = 0;
for(let i = 0; i < array.length; i++) {
countOuter++;
let min = i;
for(let j = i + 1; j < array.length; j++) {
countInner++;
if(array[j] < array[min]) {
min = j;
}
}
if(i !== min) {
countSwap++;
swap(array, i, min);
}
}
console.log('outer:', countOuter, 'inner:', countInner, 'swap:', countSwap);
return array;
}
selectionSort(arrayRandom.slice()); // => outer: 10 inner: 45 swap: 5
selectionSort(arrayOrdered.slice()); // => outer: 10 inner: 45 swap: 0
selectionSort(arrayReversed.slice()); // => outer: 10 inner: 45 swap: 5