Keep removing top element from S while the top element is smaller then or equal to arr [ i ] ( if Key is G ) element is greater then or equal to arr [ i ] ( if order is S )
while ( stack . length != 0 && ( ( order == ' ' ) ? arr [ stack [ stack . length - 1 ] ] <= arr [ i ] : arr [ stack [ stack . length - 1 ] ] >= arr [ i ] ) ) stack . pop ( ) ;