Finding a Value in an Ordered Sequence
A sequence can be searched in visitation order. A sorted sequence also gives information from each comparison that can eliminate positions.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace a linear scan
Search 8, 2, and 5 for 5. An ordinary scan tests 8 then 2 then 5 and returns position two. A first-match scan can stop at the first occurrence and provides a useful default for an unsorted sequence.
Exploit the declared order
In sorted positions holding 2, 5, and 8, knowing that a target is below the middle value eliminates the middle and everything later. That inference requires a matching sort order among the preconditions. Test an absent target between two present values.[1]
Use a repeated boundary to show what the search returns
In [2, 4, 4, 4, 9], the first position holding at least four is one. The first position strictly greater than four is four. An ordinary membership search can return any one of the three fours if that contract is sufficient. Pick the behavior needed by a caller that wants to insert another four or count the entire equal range. The lower and upper bounds delimit a half-open interval. See inclusive and exclusive tests.
Preserve the ordering needed by eliminated candidates
In a lower-bound search, if a middle value is smaller than the target, all earlier positions within the current interval are also smaller. This lets the search discard them safely. If records are sorted by case-folded names, comparisons inside the search must use the same key. Test insertion before the first value, after the last and into a repeated-key run. See sorting with key functions for the consistency requirement.