updated sorting logic