Skip to content

Commit 2554bca

Browse files
committed
Add selection sort in es6
1 parent 85c2417 commit 2554bca

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// sample of arrays to sort
2+
const arrayRandom = [9, 2, 5, 6, 4, 3, 7, 10, 1, 8];
3+
const arrayOrdered = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
4+
const arrayReversed = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
5+
6+
function selectionSort(array) {
7+
let countOuter = 0;
8+
let countInner = 0;
9+
let countSwap = 0;
10+
11+
for(let i = 0; i < array.length; i++) {
12+
countOuter++;
13+
let min = i;
14+
for(let j = i + 1; j < array.length; j++) {
15+
countInner++;
16+
if(array[j] < array[min]) {
17+
min = j;
18+
}
19+
}
20+
if(i !== min) {
21+
countSwap++;
22+
[array[i], array[min]] = [array[min], array[i]];
23+
}
24+
}
25+
26+
console.log('outer:', countOuter, 'inner:', countInner, 'swap:', countSwap);
27+
return array;
28+
}
29+
30+
selectionSort(arrayRandom.slice()); // => outer: 10 inner: 45 swap: 5
31+
selectionSort(arrayOrdered.slice()); // => outer: 10 inner: 45 swap: 0
32+
selectionSort(arrayReversed.slice()); // => outer: 10 inner: 45 swap: 5
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// array to sort
2+
const array = [9, 2, 5, 6, 4, 3, 7, 10, 1, 8];
3+
4+
function selectionSort(array) {
5+
for(let i = 0; i < array.length; i++) {
6+
let min = i;
7+
for(let j = i + 1; j < array.length; j++) {
8+
if(array[j] < array[min]) {
9+
min = j;
10+
}
11+
}
12+
if(i !== min) {
13+
[array[i], array[min]] = [array[min], array[i]];
14+
}
15+
}
16+
return array;
17+
}
18+
19+
console.log(selectionSort(array)); // => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

0 commit comments

Comments
 (0)