Programming Fundamentals/Searching Arrays

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Overview[edit | edit source]

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.[1]

Discussion[edit | edit source]

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.”[2]

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.

Pseudocode[edit | edit source]

Function Main
    Declare Integer Array ages[5]
    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[0]
    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[0] 
    For index = 1 to Size(array) - 1 
        If minimum > array[index]
            Assign minimum = array[index]
        End
    End
Return Integer minimum

Output[edit | edit source]

Maximum age is: 49
Minimum age is: 16

Key Terms[edit | edit source]

linear search
Using a loop to sequentially step through an array.
maximum
"max" is an abbreviation for maximum, which means the largest member of an array.
minimum
"min" is an abbreviation for minimum, which means the smallest member of an array.

References[edit | edit source]

  1. Wikipedia: Linear search
  2. Tony Gaddis, Judy Walters, and Godfrey Muganda, Starting Out with C++ Early Objects Sixth Edition (United States of America: Pearson – Addison Wesley, 2008) 559.