Page 4: Exactly How Much Faster Is Binary Search?
Unit 5, Lab 1, Page 4
On this page, you will compare the time required for binary search and for linear search.
Locate the block included in your project, and look inside it. Compare it to the algorithm you used to count the number of five- or seven-letter words. This block does the same computation as the
binary search
block, but it uses the linear algorithm.Use to test how much time
linear search
takes to find the word “zebra” in each length list.Length of List Linear Search
Time1000 10,000 100,000 Look at the table. How would you describe what happens to the time as the input gets bigger?
The actual amount of physical time that it takes to solve a problem depends not only on your algorithm but also on how fast your computer is and what other programs you have running, etc. Therefore, computer scientists who want to measure the speed of an algorithm do it in terms of the number of steps. For example, what we really want to know about the efficiency of the linear search
algorithm is how many times current item is compared to value (that is, how many times is called).
Add another column to your table. Assuming “zebra” is the last word in each word list, how many comparisons are made by the
linear search
algorithm for each length list?Length of List Linear Search
TimeLinear Search
Steps1000 10,000 100,000 How would you describe what happens to the number of steps as the input list gets bigger? Write your hypothesis about the pattern.
Does what happens with steps match what happens with time? That is, can you count steps as a measure of time?
The relationship between the input size and the number of steps required to solve a problem is the efficiency of the algorithm used to solve the problem.
Counting the number of steps, as you just did, is an informal, but perfectly good way to determine the efficiency of an algorithm. The formal measurement of an algorithm requires a mathematical proof.
In this course, you are mostly working with small problems, so it doesn’t matter how efficient the algorithm is. But in the real world, programmers deal with lists of billions of items, so the efficiency of an algorithm can make a huge difference.
Now, test how much time
binary search
takes to find the word “zebra” in the sorted lists, and determine how many comparisons are made by the algorithm if “zebra” is the last word in each length list.Length of List Binary Search
TimeBinary Search
Steps1000 10,000 100,000 Describe what happens to the time and the number of steps as the input list gets bigger. Write down your hypothesis.
Look back at your tables for the
linear search
and thebinary search
algorithm, and compare the two search algorithms:- Which has more blocks in its code?
- Which runs faster for large inputs?
- Which algorithm is more efficient?
What are the two requirements to use a binary search?