@@ -26,6 +26,18 @@ insertionSort = (array) => {
2626 return array
2727}
2828
29+ selectionSort = ( array ) => {
30+ for ( let i = 0 ; i < array . length - 1 ; i ++ ) {
31+ let minIndex = i ;
32+ for ( let j = i + 1 ; j < array . length ; j ++ ) {
33+ if ( array [ j ] < array [ minIndex ] ) {
34+ minIndex = j ;
35+ }
36+ }
37+ [ array [ i ] , array [ minIndex ] ] = [ array [ minIndex ] , array [ i ] ] ;
38+ }
39+ return array ;
40+ }
2941/* quickSortPartition = (array, left = 0, right = array.length - 1) => {
3042 let pivot = array[Math.floor((right + left) / 2)]
3143 let low = left
@@ -73,11 +85,11 @@ merge = (arr1, arr2) => {
7385 return sorted . concat ( arr1 . slice ( ) . concat ( arr2 . slice ( ) ) ) ;
7486}
7587
76- mergeSort = arr => {
77- if ( arr . length <= 1 ) return arr
78- let mid = Math . floor ( arr . length / 2 ) ,
79- left = mergeSort ( arr . slice ( 0 , mid ) ) ,
80- right = mergeSort ( arr . slice ( mid ) ) ;
88+ mergeSort = ( array ) => {
89+ if ( array . length <= 1 ) return array
90+ let mid = Math . floor ( array . length / 2 ) ,
91+ left = mergeSort ( array . slice ( 0 , mid ) ) ,
92+ right = mergeSort ( array . slice ( mid ) ) ;
8193
8294 return merge ( left , right ) ;
8395}
@@ -108,12 +120,20 @@ const t3 = performance.now();
108120console . log ( `Insertion sort: ${ t3 - t2 } milliseconds.` ) ;
109121console . log ( insertionArray )
110122
123+ console . log ( "SELECTION---------------------------" )
124+ let selectionArray = buildAarray ( 20 )
125+ console . log ( selectionArray )
126+ const t4 = performance . now ( ) ;
127+ selectionArray = selectionSort ( selectionArray )
128+ const t5 = performance . now ( ) ;
129+ console . log ( `Selection sort: ${ t3 - t2 } milliseconds.` ) ;
130+ console . log ( selectionArray )
131+
111132console . log ( "MERGE---------------------------" )
112133let mergeArray = buildAarray ( 20 )
113134console . log ( mergeArray )
114- const t4 = performance . now ( ) ;
135+ const t6 = performance . now ( ) ;
115136mergeArray = mergeSort ( mergeArray )
116- const t5 = performance . now ( ) ;
137+ const t7 = performance . now ( ) ;
117138console . log ( `Merge sort: ${ t5 - t4 } milliseconds.` ) ;
118139console . log ( mergeArray )
119-
0 commit comments