2.11. Ordered Sequencial Search

When arrays have been sorted, they could be searched using a slightly faster variant of the sequential sort.

The functions shown here differs from seqSearch only in replacing the != operator by a <. This causes us to exit the loop as soon as we see a value that is equal to or greater than the target. If 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 in seqSearch.

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.

In the Forum:

(no threads at this time)