@@ -2,24 +2,28 @@ const { swap } = require('./sorting-common');
22
33// tag::sort[]
44/**
5- * Selection sort - start from the first element,
6- * it tries to find any element (to the right) that could be smaller than the current index.
5+ * Selection sort - Look for smaller numbers on the right side
6+ *
7+ * It starts from the first element (index 0),
8+ * and tries to find any element (to the right)
9+ * that could be smaller than the current index.
710 * If it finds one, it will swap the positions.
11+ *
812 * Runtime: O(n^2)
913 * @param {Array|Set } collection elements to be sorted
1014 */
1115function selectionSort ( collection ) {
1216 const array = Array . from ( collection ) ;
1317
14- for ( let outer = 0 ; outer < array . length ; outer += 1 ) {
15- let selection = array [ outer ] ;
18+ for ( let left = 0 ; left < array . length ; left ++ ) {
19+ let selection = array [ left ] ;
1620
17- for ( let inner = outer + 1 ; inner < array . length ; inner += 1 ) {
18- const element = array [ inner ] ;
21+ for ( let right = left + 1 ; right < array . length ; right ++ ) {
22+ const element = array [ right ] ;
1923
2024 if ( element < selection ) {
21- swap ( array , outer , inner ) ;
22- selection = array [ outer ] ;
25+ swap ( array , left , right ) ;
26+ selection = array [ left ] ;
2327 }
2428 }
2529 }
0 commit comments