This preview has intentionally blurred sections. Sign up to view the full version.View Full Document
Unformatted text preview: Programming With Arrays - Searching 1 Programming With Arrays - Searching • Searching is the process of locating a particular item among a list of items. • Sorting is the process of arranging a sequence of items (or values) in order. For example, we might sort a list of numerical values in increasing order or a list of student names in alphabetical order. Searching a sorted list is generally much faster than searching an unsorted list. For example, it is a lot faster to search for someone’s name in an alphabetized list of names versus a nonalphabetical one. We describe two searching algorithms. 1. Sequential search: This can be used on any list of items. 2. Binary search: . This is a more efficient search than the sequential search. However, this search procedure is applicable to sorted lists only. Searching for an item in an array In general a searching problem consists of two inputs. 1. A list of items. For example, an array containing some student id s. 2. A target value for the search. For example, we want to find out whether a particular student id is in the list of student id s. When searching an array, we often want to know more than simply finding whether or not the target value is in the array. If the target value is in the array, we would like to know the index of the array element holding that target value. For example, if our target id is 2106 in a list of items represented by the following array, then we want our search function to return the index of the element ( 6 ) holding the target value. If the target value is not in the array, then we want our search function to return the index value-1 . Since-1 is not an array index, we know that the target value is not in the array. For example, if the user specifies a target value, say 9990 , the function should return-1 . Programming With Arrays - Searching 2 Sequential search The sequential search procedure is very straightforward. We start with the first element of the array and examine its contents, one element after another, until we either find the target value or have examined all elements without finding it. The following function ( sequentialSearch ) returns either the location ( index ) of the target value, or the value-1 , if the item is not in the array....
View Full Document
- Fall '08
- Sort, Array, target value