Linear Search


Sequential Search

One of the most straightforward and elementary searches is the sequential search, also known as a linear search.

As a real world example, pickup the nearest phonebook and open it to the first page of names. We're looking to find the first "Smith". Look at the first name. Is it "Smith"? Probably not (it's probably a name that begins with 'A'). Now look at the next name. Is it "Smith"? Probably not. Keep looking at the next name until you find "Smith".

The above is an example of a sequential search. You started at the beginning of a sequence and went through each item one by one, in the order they existed in the list, until you found the item you were looking for. Of course, this probably isn't how you normally look up a name in the phonebook; we'll cover a method similar to the way you probably look up phone numbers later in this guide.

Now we'll look at this as related to computer science. Instead of a phonebook, we have an array. Although the array can hold data elements of any type, for the simplicity of an example we'll just use an array of integers, like the following:

Figure %: The array we're searching
Lets search for the number 3. We start at the beginning and check the first element in the array. Is it 3?
Figure %: Is the first value 3?
No, not it. Is it the next element?
Figure %: Is the second value 3?
Not there either. The next element?
Figure %: Is the third value 3?
Not there either. Next?
Figure %: Is the fourth value 3? Yes!
We found it!!! Now you understand the idea of linear searching; we go through each element, in order, until we find the correct value.

Take a Study Break

SparkLife

Everything I know about Dr. Who I learned from the hype

Tell me, is it all correct?

SparkLife

Was your first kiss a dud?

Relive the awkwardness with Dear Albert!

SparkLife

SNOW WHITE LIKE CRAZY

Click here for pics, embarrassing interviews, and more!

SparkLife

It's Jobs Week on SparkLife

Plan your future here!

SparkLife

Hate being the third wheel?

Jono can help

Geek out!

The MindHut

Scott Pilgrim's Precious Little Life

Is the Scott Pilgrim comic as good as the movie?

The MindHut

BOOK REVIEW: Insurgent by Veronica Roth

A scary look into the future!

The MindHut

DC is Better Than Marvel

Which side are you on?

The MindHut

In Need of an Ongoing: Masters of Evil

Should these baddies have their own series?

The MindHut

5 Books That Made Us Afraid of Robots

They're coming for us!

The Book

Cover image

Read What You Love, Anywhere You Like

Get Our FREE NOOK Reading Apps