A sorting algorithm that slightly improves on selection sort | Javascript program to implement min max selection sort . ; Shifting the min . ; Shifting the max . The equal condition happens if we shifted the max to arr [ min_i ] in the previous swap . ; Driver code
function swap ( arr , xp , yp ) { var temp = arr [ xp ] ; arr [ xp ] = arr [ yp ] ; arr [ yp ] = temp ; } function minMaxSelectionSort ( arr , n ) { for ( var i = 0 , j = n - 1 ; i < j ; i ++ , j -- ) { var min = arr [ i ] ; var max = arr [ i ] ; var min_i = i ; var max_i = i ; for ( var k = i ; k <= j ; k ++ ) { if ( arr [ k ] > max ) { max = arr [ k ] ; max_i = k ; } else if ( arr [ k ] < min ) { min = arr [ k ] ; min_i = k ; } } swap ( arr , i , min_i ) ; if ( arr [ min_i ] == max ) swap ( arr , j , min_i ) ; else swap ( arr , j , max_i ) ; } } var arr = [ 23 , 78 , 45 , 8 , 32 , 56 , 1 ] ; var n = 7 ; minMaxSelectionSort ( arr , n ) ; document . write ( " " ) ; for ( var i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) ; document . write ( " " ) ;