Skip to content

Commit ee387c3

Browse files
committed
📦 NEW: Add Selection sort
Selection sort algorithm implementation in javascript
1 parent 4894c44 commit ee387c3

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

Sorts/selectionSort.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/*
2+
3+
Selection sort is fairly simple. Assume the left part of your array is
4+
sorted and right part is unsorted. Inititally the sorted(left) part is
5+
empty. Now select the smallest element from the unsorted(right) part and
6+
swap it with the first element of the unsorted(right) part. Now this element
7+
is sorted, move to the next iteration and repeat without touch the sorted(left)
8+
part.
9+
10+
*/
11+
function selectionSort(arr) {
12+
for (let i = 0; i < arr.length; i++) {
13+
let firstOfUnsorted = arr[i];
14+
15+
// find the index of the smallest element in the unsorted part
16+
let minIndex = i;
17+
for (let j = i + 1; j < arr.length; j++) {
18+
if (arr[minIndex] > arr[j]) {
19+
minIndex = j;
20+
}
21+
}
22+
23+
// swapping the minimum with first element of unsorted part
24+
arr[i] = arr[minIndex];
25+
arr[minIndex] = firstOfUnsorted;
26+
}
27+
return arr;
28+
}
29+
30+
// This has the time complexity of O(n^2)

0 commit comments

Comments
 (0)