Skip to content

Commit 377f175

Browse files
Added selection sort
1 parent 9f465a2 commit 377f175

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

selection-sort.js

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
const findSmallest = (arr) => {
2+
let smallest = arr[0];
3+
let smallestIndex = 0;
4+
for (let i=0; i<arr.length; i++){
5+
if(arr[i]<smallest){
6+
smallest = arr[i];
7+
smallestIndex = i;
8+
}
9+
}
10+
return smallestIndex;
11+
}
12+
13+
const selectionSort = (arr) => {
14+
let newArr = [];
15+
let smallest;
16+
let length = arr.length;
17+
for(let i = 0; i<length; i++){
18+
smallest = findSmallest(arr);
19+
newArr.push(arr[smallest]);
20+
arr.splice(smallest, 1);
21+
}
22+
return newArr;
23+
}
24+
25+
console.log(selectionSort([5, 3, 6, 2, 10]));

0 commit comments

Comments
 (0)