Updated logic for sorting getAncestors result.