Enhanced sort_stack algorithm