TODAY WE START DOING REAL COMPUTER SCIENCE!!!!!

We will look at algorithms to solve general problems, we will study how to implement them, and then show how to analyze the algorithms that we create.

Searching

Input: Array A[0..n-1] of n elements, and a value x.
Output: An index i such that A[i] == x, or -1 if A[i] != x for all 0 <= i < n.

See Demo linearSearch0.cpp

Can improve on previous implementation. See Demo linearSearch1.cpp

Can improve on previous implementation still. See Demo linearsearch2.cpp

This is about the best we can do if we have no further information about the array. But what if...

The array A is sorted

Array A is sorted if

A[0] <= A[1] <= A[2] <= ... <= A[N-2] <= A[N-1] .
For example, the following array is sorted:

Suppose we search for the element 12, which is not in the above array. We can stop when we get to A[3] == 13 because 12 < 13 and all the entries after A[3] are >= 13. So how do we implement this improvement?

Let's try Demo linearSearch3.cpp

So is it possible to combine both ideas and use a sentinel with a sorted array? You bet! Graphically, we would alter our previous sorted array to be:

And the code is in linearSearch4.cpp

To Index Previous Next