Skip to content

Commit 5268082

Browse files
authored
fix indexof with sorted flag not returning first index (#800)
1 parent cee9384 commit 5268082

File tree

2 files changed

+10
-15
lines changed

2 files changed

+10
-15
lines changed

src/algorithm/dyadic/search.rs

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -232,26 +232,20 @@ impl<T: ArrayValue> Array<T> {
232232
if haystack.rank() - needle.rank() == 1 {
233233
if haystack.meta.is_sorted_up() {
234234
// Binary search
235-
if haystack.row_count() == 0 {
236-
return Ok(default.into());
237-
}
238235
let needle_slice = ArrayCmpSlice(needle.data.as_slice());
239236
let mut l = 0;
240-
let mut r = haystack.row_count().saturating_sub(1);
241-
let mut res = None;
242-
while l <= r {
237+
let mut r = haystack.row_count();
238+
while l < r {
243239
let mid = l + (r - l) / 2;
244-
match ArrayCmpSlice(haystack.row_slice(mid)).cmp(&needle_slice) {
245-
Ordering::Equal => {
246-
res = Some(mid);
247-
break;
248-
}
249-
Ordering::Less => l = mid + 1,
250-
Ordering::Greater if mid == 0 => break,
251-
Ordering::Greater => r = mid - 1,
240+
if ArrayCmpSlice(haystack.row_slice(mid)) < needle_slice {
241+
l = mid + 1;
242+
} else {
243+
r = mid;
252244
}
253245
}
254-
(res.map(|i| i as f64).unwrap_or(default)).into()
246+
let found = l < haystack.row_count()
247+
&& ArrayCmpSlice(haystack.row_slice(l)) == needle_slice;
248+
if found { l as f64 } else { default }.into()
255249
} else {
256250
// Linear search
257251
(haystack

tests/optimized.ua

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,7 @@ F ← ⬚10(/+◌1⊞(ׯ))
340340
⍤⤙≍ [1 1 0] ⧈≠ [1 2 3 3]
341341
◌≡(⍆∘) ≡⊏⊙¤ ⊸(≡⍏ gen⊙0 ⊟100⧻) °△21_2
342342
⍤⤙≍ 1 /↥ [NaN 1]
343+
⍤⤙≍0 ⊗1 ⍆[1 1 1 1 1 1 1 1]
343344

344345
# Range start
345346
⍤⤙≍ [1 2 3 4 5] ⇡₁5

0 commit comments

Comments
 (0)