Skip to main content
Logo image

Section 13.1 Searching Algorithms

Computers store vast amounts of data. One of the strengths of computers is their ability to find things quickly. This ability is called searching. For the AP CSA exam you will need to know both linear (sequential) search and binary search algorithms.
The following video is also on YouTube at https://youtu.be/DHLCXXX1OtE. It introduces the concept of searching including sequential search and binary search.
  • Linear search is a standard algorithm that checks each element in order until the desired value is found or all elements in the array or ArrayList have been checked. Linear search algorithms can begin the search process from either end of the array or ArrayList.
  • Binary search can only be used on data that has been sorted or stored in order. It checks the middle of the data to see if that middle value is less than, equal, or greater than the desired value and then based on the results of that it narrows the search. It cuts the search space in half each time.
If binary search requires the values in an array or list to be sorted, how can you do that? There are many sorting algorithms which are covered in the next lesson.

Subsection 13.1.2 Linear Search with 2D Arrays

We can also apply the linear search algorithm to data in a 2D array. We can loop through each row of the 2D array and then apply the linear search algorithm to each row to find an element. The code below demonstrates this with a 2D array of integers. Click on the Code Lens button to step through this code. Then, change it to work with a 2D array of Strings. Remember to use the equals method to compare Strings.

Activity 13.1.6.

What will the following code print? Click on the Code Lens button to step through this code. Can you change the code to work for a String 2D array instead of an int array? Note that the indices row and col will still be ints. Remember to use the equals method to compare Strings.

Subsection 13.1.4 Runtimes

How do we choose between two algorithms that solve the same problem? They usually have different characteristics and runtimes which measures how fast they run. For the searching problem, it depends on your data.
Binary search is much faster than linear search, especially on large data sets, but it can only be used on sorted data. Often with runtimes, computer scientist think about the worst case behavior. With searching, the worst case is usually if you cannot find the item. With linear search, you would have to go through the whole array before realizing that it is not there, but binary search is much faster even in this case because it eliminates half the data set in each step. We can measure an informal runtime by just counting the number of steps.
Here is a table that compares the worst case runtime of each search algorithm given an array of n elements. The runtime here is measured as the number of times the loop runs in each algorithm or the number of elements we need to check in the worst case when we don’t find the item we are looking for. Notice that with linear search, the worst case runtime is the size of the array n, because it has to look through the whole array. For the binary search runtime, we can calculate the number of times you can divide n in half until you get to 1. So, for example 8 elements can be divided in half to narrow down to 4 elements, which can be further divided in half to narrow down to 2 elements, which can be further divided in half to get down to 1 element, and then if that is wrong, to 0 elements, so that is 4 divisions or guesses to get the answer (8->4->2->1->0). In the table below, every time we double the size of N, we need at most one more guess or comparison with binary search. It’s much faster than linear search!
Table 13.1.2.
N Linear Search Binary Search
2 2 comparisons 2 comparisons
4 4 3
8 8 4
16 16 5
100 100 7
Runtimes can be described with mathematical functions. For an array of size n, linear search runtime is a linear function, and binary search runtime is a function of log base 2 of n (or log n + 1 comparisons). This is called the big-O runtime function in computer science, for example O(log n) vs. O(n). You can compare the growth of functions like n and \(\log_{2}n\) as \(n\text{,}\) the data size, grows and see that binary search runs much faster for any \(n\text{.}\) You don’t need to know the log n runtime growth function for the AP exam, but you should be able to calculate how many steps binary search takes for a given n by counting how many times you can divide it in half. Or you can start at 1 and keep a count of how many times you can double it with the powers of two (1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, etc.) until you reach a number that is slightly above n.

Activity 13.1.9.

Which will cause the shortest execution of a binary search looking for a value in an array of integers?
  • The value is the first one in the array
  • This would be true for sequential search, not binary.
  • The value is in the middle of the array
  • If the value is in the middle of the array the binary search will return after one iteration of the loop.
  • The value is the last one in the array
  • How would that be the shortest in a binary search?
  • The value isn’t in the array
  • This is true for the longest execution time, but we are looking for the shortest.

Activity 13.1.10.

Which of the following conditions must be true in order to search for a value using binary search?
I. The values in the array must be integers.
II. The values in the array must be in sorted order.
III. The array must not contain duplicate values.
  • I only
  • You can use a binary search on any type of data that can be compared, but the data must be in order.
  • I and II
  • You can use a binary search on any type of data that can be compared.
  • II only
  • The only requirement for using a Binary Search is that the values must be ordered.
  • II and III
  • The array can contain duplicate values.

Activity 13.1.11.

How many times would the loop in the binary search run for an array int[] arr = {2, 10, 23, 31, 55, 86} with binarySearch(arr,55)?
  • It will first compare with the value at index 2 and then index 4 and then return 4.
  • This would be true if we were looking for 23.
  • This would be true if we were looking for 31.

Activity 13.1.12.

If you had an ordered array of size 500, what is the maximum number of iterations required to find an element with binary search?
  • approximately 15 times
  • How many times can you divide 500 in half?
  • approximately 9 times
  • You can divide 500 in half, 9 times, or you can observe that 2^9 = 512 which is slightly bigger than 500.
  • 500 times
  • How many times can you divide 500 in half?
  • 2 times
  • How many times can you divide 500 in half?

Subsection 13.1.5 Coding Challenge: Search Runtimes

Let’s go back to the spellchecker that we created with arrays. Here is a version of the spellchecker below that reads the dictionary file into an ArrayList. The advantage of using an ArrayList instead of an array for the dictionary is that we do not need to know or declare the size of the dictionary in advance.
In the spellchecker challenge, we used linear search to find a word in the dictionary. However, the dictionary file is actually in alphabetical order. We could have used a much faster binary search algorithm! Let’s see how much faster we can make it.
Write a linear search method and a binary search method to search for a given word in the dictionary using the code in this lesson as a guide. You will need to use size and get(i) instead of [] to get an element in the ArrayList dictionary at index i. You will need to use the equals and compareTo methods to compare Strings. Have the methods return a count of how many words they had to check before finding the word or returning.

Project 13.1.13.

This spellchecker uses an ArrayList for the dictionary. Write a linearSearch(word) and a binarySearch(word) method. Use get(i), size(), equals, and compareTo. Return a count of the number of words checked.
Run your code with the following test cases and record the runtime for each word in this Google document (do File/Make a Copy) also seen below to record your answers.
What do you notice? Which one was faster in general? Were there some cases where each was faster? How fast were they with misspelled words? Record your answers in the window below.

Subsection 13.1.6 Summary

  • (AP 4.14.A.1) Linear search algorithms are standard algorithms that check each element in order until the desired value is found or all elements in the array or ArrayList have been checked. Linear search algorithms can begin the search process from either end of the array or ArrayList.
  • (AP 4.14.A.2) When applying linear search algorithms to 2D arrays, each row must be accessed then linear search applied to each row of the 2D array.
  • The binary search algorithm starts at the middle of a sorted array or ArrayList and eliminates half of the array or ArrayList in each iteration until the desired value is found or all elements have been eliminated.
  • (AP 4.17.B.1 preview) Data must be in sorted order to use the binary search algorithm.
  • (AP 4.17.B.2 preview) Binary search is typically more efficient than linear search.
  • (AP 4.17.B.3 preview) The binary search algorithm can be written either iteratively or recursively. (The recursive solution will be presented in lesson 4.17).
  • Informal run-time comparisons of program code segments can be made using statement execution counts.
You have attempted of activities on this page.