1
- //Simple Selection Sort implementation
2
- function selectionSort ( arr ) {
3
- var len = arr . length ;
4
-
5
- /* advance the position through the entire array */
6
- /* (could do i < n-1 because single element is also min element) */
7
- for ( var i = 0 ; i < len - 1 ; i ++ ) {
8
- // find the min element in the unsorted a[i .. n-1]
9
-
10
- var currentMin = i ; // assume the min is the first element
11
- // test against elements after i to find the smallest
12
- for ( var j = i + 1 ; j < len ; j ++ )
13
- {
14
- // if this element is less, then it is the new minimum
15
- if ( arr [ j ] < arr [ currentMin ] ) //To sort in decreasing order just change the comparison operator to '>'
16
- currentMin = j ; // found new minimum; remember its index
17
- }
18
-
19
- if ( currentMin != i ) //if the current_Min is equal to i, then it is in right position already
20
- {
21
- //Swap the values
22
- tmp = arr [ i ] ;
23
- arr [ i ] = arr [ currentMin ] ;
24
- arr [ currentMin ] = tmp ;
25
- }
26
- }
27
-
28
- return arr ;
1
+ /* Selection Sort implementation in JavaScript */
2
+ function selectionSort ( arr ) {
3
+ var len = arr . length ;
4
+
5
+ /* advance the position through the entire array */
6
+ /* (could do i < n-1 because single element is also min element) */
7
+ for ( var i = 0 ; i < len - 1 ; i ++ ) {
8
+ // find the min element in the unsorted a[i .. n-1]
9
+
10
+ var currentMin = i ; // assume the min is the first element
11
+ // test against elements after i to find the smallest
12
+ for ( var j = i + 1 ; j < len ; j ++ ) {
13
+ // if this element is less, then it is the new minimum
14
+ if ( arr [ j ] < arr [ currentMin ] ) //To sort in decreasing order just change the comparison operator to '>'
15
+ currentMin = j ; // found new minimum; remember its index
16
+ }
17
+
18
+ if ( currentMin != i ) //if the current_Min is equal to i, then it is in right position already
19
+ {
20
+ //Swap the values
21
+ tmp = arr [ i ] ;
22
+ arr [ i ] = arr [ currentMin ] ;
23
+ arr [ currentMin ] = tmp ;
24
+ }
25
+ }
26
+
27
+ return arr ;
29
28
}
30
29
31
30
/******************* Testing Selection sort algorithm *********************/
@@ -35,13 +34,13 @@ function selectionSort(arr){
35
34
* Using Math.round() will give you a non-uniform distribution!
36
35
*/
37
36
function getRandomInt ( min , max ) {
38
- return Math . floor ( Math . random ( ) * ( max - min + 1 ) ) + min ;
37
+ return Math . floor ( Math . random ( ) * ( max - min + 1 ) ) + min ;
39
38
}
40
39
41
40
var arr = [ ] ;
42
41
43
- for ( var i = 0 ; i < 10 ; i ++ ) { //initialize a random integer unsorted array
44
- arr . push ( getRandomInt ( 1 , 100 ) ) ;
42
+ for ( var i = 0 ; i < 10 ; i ++ ) { //initialize a random integer unsorted array
43
+ arr . push ( getRandomInt ( 1 , 100 ) ) ;
45
44
}
46
45
47
46
console . log ( "Unsorted array: " ) ;
0 commit comments