1
+ /*SELECTION SORT:
2
+ * inplace comparison-based sorting algorithm.
3
+ * list is divided into two parts, the sorted part at the left end and the unsorted part at the right end.
4
+ * The smallest element from the unsorted array is found and swapped with the leftmost element.
5
+ ie, added to the sorted array.
6
+ * This process continues moving unsorted array boundary by one element to the right.
7
+ */
8
+
9
+ //importing readline module for dynamic input
10
+ var readline = require ( 'readline' ) ;
11
+ //initialising inputstream and outstream to process.stdin and process.stdout respectively.
12
+ var rl = readline . createInterface (
13
+ process . stdin , process . stdout ) ;
14
+
15
+ const selectionSort = ( arr ) => {
16
+ let n = arr . length ;
17
+ // i is the current index
18
+ for ( let i = 0 ; i < n - 1 ; i ++ ) {
19
+ //minPos stores the position of smallest element
20
+ let minPos = i ;
21
+
22
+ //finding the minimum element from arr.
23
+ for ( let j = i + 1 ; j < n ; j ++ ) {
24
+ if ( arr [ j ] < arr [ minPos ] ) {
25
+ minPos = j ;
26
+ }
27
+ }
28
+ //swapping current element and smallest element;
29
+ let temp = arr [ minPos ] ;
30
+ arr [ minPos ] = arr [ i ] ;
31
+ arr [ i ] = temp ;
32
+ }
33
+ return arr ;
34
+ }
35
+
36
+ //Reading input from console as a string and converting it to array
37
+ rl . question ( 'Enter array elements comma separated: ' , ( input ) => {
38
+ let numbers = input . split ( "," ) ;
39
+ numbers = numbers . map ( ( x ) => parseInt ( x ) ) ;
40
+ console . log ( selectionSort ( numbers ) ) ;
41
+ rl . close ( ) ;
42
+ } ) ;
43
+
44
+ /*
45
+ INPUT
46
+ Enter array elements comma separated:
47
+ 1, 8, 7, 61, 5, 4, 11
48
+ OUTPUT
49
+ 1,4,5,7,8,11,61
50
+
51
+ Time Complexity - O(n^2)
52
+ Space Complexity - O(1)
53
+ */
0 commit comments