Skip to content

Commit c114636

Browse files
committed
added file
1 parent 32375a8 commit c114636

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Sorting/selection_sort.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
function selectionSort(arr) {
2+
let min;
3+
4+
//start passes.
5+
for (let i = 0; i < arr.length; i++) {
6+
//index of the smallest element to be the ith element.
7+
min = i;
8+
9+
//Check through the rest of the array for a lesser element
10+
for (let j = i + 1; j < arr.length; j++) {
11+
if (arr[j] < arr[min]) {
12+
min = j;
13+
}
14+
}
15+
16+
//compare the indexes
17+
if (min !== i) {
18+
//swap
19+
[arr[i], arr[min]] = [arr[min], arr[i]];
20+
}
21+
}
22+
23+
return arr;
24+
}
25+
26+
console.log(selectionSort([29, 72, 98, 13, 87, 66, 52, 51, 36]));

0 commit comments

Comments
 (0)