6.6: Searching Arrays
- Page ID
Linear search or sequential search is a method for finding a target value within a list. It sequentially checks each element of the list for the target value until a match is found or until all the elements have been searched.
Finding a specific member of an array means searching the array until the member is found. It’s possible that the member does not exist and the programmer must handle that possibility within the logic of his or her algorithm.
“The linear search is a very simple algorithm. Sometimes called a sequential search, it uses a loop to sequentially step through an array, starting with the first element. It compares each element with the value being searched for, and stops when either the value is found or the end of the array is encountered. If the value being searched for is not in the array, the algorithm will search to the end of the array.”
Two specific linear searches can be made for the maximum (largest) value in the array or the minimum (smallest) value in the array. Maximum and minimum are also known as max and min. Note that the following max and min functions assume an array size >= 1.
Function Main Declare Integer Array ages Declare Integer maximum Declare Integer minimum Assign ages = [49, 48, 26, 19, 16] Assign maximum = max(ages) Assign minimum = min(ages) Output "Maximum age is: " & maximum Output "Minimum age is: " & minimum End Function max (Integer Array array) Declare Integer maximum Declare Integer index Assign maximum = array For index = 1 to Size(array) - 1 If maximum < array[index] Assign maximum = array[index] End End Return Integer maximum Function min (Integer Array array) Declare Integer minimum Declare Integer index Assign minimum = array For index = 1 to Size(array) - 1 If minimum > array[index] Assign minimum = array[index] End End Return Integer minimum
Maximum age is: 49 Minimum age is: 16
- linear search
- Using a loop to sequentially step through an array.
- Aka max or the largest member of an array.
- Aka min or the smallest member of an array.
- cnx.org: Programming Fundamentals – A Modular Structured Approach using C++
- Wikiversity: Computer Programming