When arrays have been sorted, they could be searched using a slightly faster variant of the sequential sort.
The functions shown here differs from
in replacing the
!= operator by a
causes us to exit the loop as soon as we see a value that is equal to
or greater than the
arr is sorted, then encountering a value greater than the
target would imply that the
target value is
not actually in the array,
Without this assurance, we would need to search the entire array
if the element being looked for was not present, which is what happens
The worst case for the two algorithms is the same. We might guess, however, that the ordered search does better “on average” when applied to sorted data. Of course, if the data in the array isn't sorted, then we can't use ordered search at all.