Skip to content

Commit 507e514

Browse files
committed
chore: replace if-else by match with guard
1 parent bdaf9ef commit 507e514

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

src/searching/ternary_search.rs

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -72,18 +72,20 @@ fn match_compare<T: Ord>(
7272

7373
// Handling the edge case where the search narrows down to a single element
7474
if first_mid == second_mid && first_mid == *left {
75-
if arr[*left] != *item {
76-
*left += 1;
77-
return false;
78-
}
79-
80-
return true;
75+
return match &arr[*left] {
76+
x if x == item => true,
77+
_ => {
78+
*left += 1;
79+
false
80+
}
81+
};
8182
}
8283

8384
let cmp_first_mid = item.cmp(&arr[first_mid]);
8485
let cmp_second_mid = item.cmp(&arr[second_mid]);
8586

8687
match (is_asc, cmp_first_mid, cmp_second_mid) {
88+
// If the item matches either midpoint, it returns the index
8789
(_, Ordering::Equal, _) => {
8890
*left = first_mid;
8991
return true;
@@ -92,10 +94,15 @@ fn match_compare<T: Ord>(
9294
*left = second_mid;
9395
return true;
9496
}
97+
// If the item is smaller than the element at first_mid (in ascending order)
98+
// or greater than it (in descending order), it narrows the search to the first third.
9599
(true, Ordering::Less, _) | (false, Ordering::Greater, _) => {
96100
*right = first_mid.saturating_sub(1)
97101
}
102+
// If the item is greater than the element at second_mid (in ascending order)
103+
// or smaller than it (in descending order), it narrows the search to the last third.
98104
(true, _, Ordering::Greater) | (false, _, Ordering::Less) => *left = second_mid + 1,
105+
// Otherwise, it searches the middle third.
99106
(_, _, _) => {
100107
*left = first_mid + 1;
101108
*right = second_mid - 1;

0 commit comments

Comments
 (0)