Searching an Array

Consider the list below.

Jay 1974
Debbie 1976
Ian 1999
Greg 1954
Carol 2011
Sam 2000

In the lesson on arrays we saw how to read the names and years into an array of names and an array of years, and then printed the entire list showing each person's name and age.

We can picture these two arrays as shown below:

index names years
0 Jay 1974
1 Debbie 1976
2 John 1918
3 Greg 1954
4 Carol 2011
5 Sam 2000

If we would like to know what year Greg was born, we would type in the name "Greg", then search the names array for Greg. When we find Greg in position 3, then we can print the year born from years[3]. Two arrays that correspond to each other are called parallel arrays. Note that there was room in the array for 20 people but there are actually only 6 (0..5). When we search this array we only search from 0 to 5.

The list of names above is not sorted into alphabetical order. When we search an unordered list, we have no choice but to search the entire array until we find what we are looking for or reach the end of the list using the actual number of names. This type of search is called a sequential search.

NEXT: The sequential search code