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 append it to the input stack ; append temp in tempory of stack ; append array elements to stack ; Sort the temporary stack ; Put stack elements in arrp [ ] ; Driver code
def sortStack ( input ) : NEW_LINE INDENT tmpStack = [ ] NEW_LINE while ( len ( input ) > 0 ) : NEW_LINE INDENT tmp = input [ - 1 ] NEW_LINE input . pop ( ) NEW_LINE while ( len ( tmpStack ) > 0 and tmpStack [ - 1 ] < tmp ) : NEW_LINE INDENT input . append ( tmpStack [ - 1 ] ) NEW_LINE tmpStack . pop ( ) NEW_LINE DEDENT tmpStack . append ( tmp ) NEW_LINE DEDENT return tmpStack NEW_LINE DEDENT def sortArrayUsingStacks ( arr , n ) : NEW_LINE INDENT input = [ ] NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT input . append ( arr [ i ] ) NEW_LINE i = i + 1 NEW_LINE DEDENT tmpStack = sortStack ( input ) NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT arr [ i ] = tmpStack [ - 1 ] NEW_LINE tmpStack . pop ( ) NEW_LINE i = i + 1 NEW_LINE DEDENT return arr NEW_LINE DEDENT arr = [ 10 , 5 , 15 , 45 ] NEW_LINE n = len ( arr ) NEW_LINE arr = sortArrayUsingStacks ( arr , n ) NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE i = i + 1 NEW_LINE DEDENT