The Slowest Sorting Algorithms | Function to implement stooge sort ; Base Case ; If first element is smaller than last element , swap them ; If there are more than 2 elements in the array ; Recursively sort the first 2 / 3 elements ; Recursively sort the last 2 / 3 elements ; Recursively sort the first 2 / 3 elements again ; Driver Code ; Function Call ; Display the sorted array
function stoogesort ( arr , l , h ) { if ( l >= h ) return ; if ( arr [ l ] > arr [ h ] ) { let temp = arr [ l ] ; arr [ l ] = arr [ h ] ; arr [ h ] = temp ; } if ( h - l + 1 > 2 ) { let t = Math . floor ( ( h - l + 1 ) / 3 ) ; stoogesort ( arr , l , h - t ) ; stoogesort ( arr , l + t , h ) ; stoogesort ( arr , l , h - t ) ; } } let arr = [ 2 , 4 , 5 , 3 , 1 ] ; let N = arr . length ; stoogesort ( arr , 0 , N - 1 ) ; for ( let i = 0 ; i < N ; i ++ ) { document . write ( arr [ i ] + " " ) ; }