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 ( ! S . empty ( ) && ( ( order == ' G ' ) ? arr [ S . top ( ) ] <= arr [ i ] : arr [ S . top ( ) ] >= arr [ i ] ) ) S . pop ( ) ;