Click to see the rest of the Algorithms section :
Searching Algorithms, like sorting can range from very simple to complex. One thing that you will need to be aware of when selecting a searching algorithm is whether the data that you are searching is already sorted.
Imagine that you have been asked to find a particular book on a bookshelf 10m long (long shelf!). What method would you choose to locate the book in the shortest time possible?
You could start at the beginning and check each book in turn until you found the book that you were looking for…
This is a legitimate algorithm that will eventually help you find your book. This is known as Linear Search and is used when we have a small number of items to search through and the items in our list are not sorted. In pseudocode, the algorithm would look like:
Book <-- "Teach All About IT - The Definitive Guide"
WHILE (myShelf[i] <> Book) AND (myShelf[i] < LENGTH(myShelf)) DO
i <-- i+1
But what if the books on the shelf were in order? With a 10 meter bookshelf, surely there is a better way to search for the book that we want? There is – it’s called Binary Search
Binary Search is also known as Divide & Conquer because every time we try an option, if we follow the rules of the algorithm the list is reduced by half. In this way, a list of 100 items can be sorted through in just 7 steps!
In order to use Binary Search, we must start with a sorted list and select the middle item (if the list has an even number of items, then middle – 1).
We then pose the question “Is the book higher than this book?”
IF yes, then it’s in the top half of the shelf, otherwise it’s in the bottom half.
Try this for yourself by guessing a random number between 1 & 100 using the following algorithm:
Found <- False
Bottom <-- 1
Top <-- 100
WHILE Found <- False
Mid <-- (Bottom + Top)/2
IF myList[Mid] > Search THEN
Top <-- Mid-1
ELSE IF myList[Mid] < Search THEN
Bottom <-- Mid +1
Found <-- True
Find this page helpful? Share the love on your social media mentioning @TeachAllAboutIT and we’ll enter you in our monthly draw to win a gift voucher for any product on the site!
More For Members
Sign Up For Membership Today
|Individual Teacher||£3.99 per Month. After your initial payment, your first payment is Free.||Select|
|Individual Student||£2.50 per Month. After your initial payment, your first payment is Free.||Select|
|Whole School||£12.50 per Month.||Select|
|iGCSE Computer Science Distance Learning (Feb Start)||£21.00 now and then £21.00 per Month for 15 more Months.||Select|
|iGCSE Computer Science Distance Learning (Sept Start)||£21.00 now and then £21.00 per Month for 15 more Months.||Select|