Sorting array using Stacks | This function return the sorted stack ; pop out the first element ; while temporary stack is not empty and top of stack is smaller than temp ; pop from temporary stack and push it to the input stack ; push temp in tempory of stack ; Push array elements to stack ; Sort the temporary stack ; Put stack elements in arrp [ ] ; main function
function sortStack ( input ) { var tmpStack = [ ] ; while ( input . length != 0 ) { var tmp = input [ input . length - 1 ] ; input . pop ( ) ; while ( tmpStack . length != 0 && tmpStack [ tmpStack . length - 1 ] < tmp ) { input . push ( tmpStack [ tmpStack . length - 1 ] ) ; tmpStack . pop ( ) ; } tmpStack . push ( tmp ) ; } return tmpStack ; } function sortArrayUsingStacks ( arr , n ) { var input = [ ] ; for ( var i = 0 ; i < n ; i ++ ) input . push ( arr [ i ] ) ; var tmpStack = sortStack ( input ) ; for ( var i = 0 ; i < n ; i ++ ) { arr [ i ] = tmpStack [ tmpStack . length - 1 ] ; tmpStack . pop ( ) ; } } var arr = [ 10 , 5 , 15 , 45 ] ; var n = arr . length ; sortArrayUsingStacks ( arr , n ) ; for ( var i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) ;