This book is now obsolete Please use CSAwesome instead.
13.2. Sequential Search¶
Sequential search is the only method that can be used to find a value in unsorted data. It usually starts at the first element and walks through the array or list until it finds the value it is looking for and returns the index it found it at, or it loops until the end of the array or list and then it returns a -1 to show that it didn’t find the value in the array or list.
The code for sequentialSearch
below is from the AP CS A course description.
To see this executing using the Java Visualizer click on the following link SequentialSearch
- The value is the first one in the array
- This would be true for the shortest execution. This would only take one execution of the loop.
- The value is in the middle of the array
- Why would this be the longest execution?
- The value is the last one in the array
- There is one case that will take longer.
- The value isn't in the array
- A sequential search loops through the elements of an array or list starting with the first and ending with the last and returns from the loop as soon as it finds the passed value. It has to check every value in the array when the value it is looking for is not in the array.
13-2-2: Which will cause the longest execution of a sequential search looking for a value in an array of integers?
- The value is the first one in the array
- This would only take one execution of the loop.
- The value is in the middle of the array
- Are you thinking of binary search?
- The value is the last one in the array
- This would be true if you were starting at the last element, but the algorithm in the course description starts with the first element.
- The value isn't in the array
- This is true for the longest execution time, but we are looking for the shortest.
13-2-3: Which will cause the shortest execution of a sequential search looking for a value in an array of integers?
Of course you can also look for a string in an array or list. But, when you look for a string be sure to use equals
rather than ==
. Remember that ==
is only true when the two references refer to the same object, while equals
returns true if the characters in the two objects are the same.
To see this executing using the Java Visualizer click on this String-SeqSearch