File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed
Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change 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)
You can’t perform that action at this time.
0 commit comments