Toggle menu
Toggle preferences menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

Linear search: Difference between revisions

From Coderwiki
new
(No difference)

Revision as of 11:38, 9 August 2025

A linear search is a search algorithm which simply steps through each element of an array or list and checks if it matches the target value.

Example: linear search in Python

This will print the index of the first instance of the number 9 in the list.

It would make more sense to use Python's enumerate method here, but we don't use it as it is not necessarily found in other languages (and this wiki aims to be as generic as possible).

data = [3, 4, 7, 9, 1, 2, 9, 12]
target = 9

for i in range(len(data)): # loop over indices of data list
    element = data[i] # get the element at the current index
    if element == target: # check if element matches target
        print(i) # print index of first occurance
        break # stop after first instance