Lecture Notes for Introduction to Computer Science II
21 June 2001 - Array Algorithms for Searching
- arrays have a regular structure
- an value followed by an array
- an array followed by a value
- a value between two arrays
- in general, a single value and smaller arrays
- note the smaller arrays have the same structure
- array algorithms can have a structure similar to arrays
- an algorithm is a recipe for performing a calculation
-
do_something(a[1..n])
if do_something(a[1]) is o.k. return
do_something(a[2..n])
-
do_something(a[1..n])
do_something(a[2..n])
if do_something(a[1]) is o.k. return
- array pictures are helpful in understanding these algorithms
- example - linear search
- the problem - given an array a and a value x, return the index of x in
a or -1 if x doesn't appear in a.
- which algorithm form to use
- the value doesn't interact with the array - use the first form.
-
int find(a[1..n], x)
if a[1] == x return i
if 1 == n return -1
return find(a[2..n], x)
- what's the array picture?
- example - star strings
- problem - return the leftmost index of the longest sequence if stars in
a string
- which algorithm form to use
- the value does interact with the array, use the second form
-
int star_string(a[1..n])
i = star_string(a[1..n - 1])
if a[1..n] forms a new longer star string
set i properly
return i
- what's the array picture?
This page last modified on 21 June 2001.