Linear Search Algorithm

by Devansh


Posted on 23 Oct 2018 11:10:09 (3 weeks ago)




There are so many ways to find an element in a data structure i.e. array or list in Python. This is one of the easiest search algorithms we refer to as a linear or sequential searches. As you see the name it clearly indicates that these algorithms look at the elements sequentially or in other word we can say that it will look at the element one by one in the order in which they appear in the data structure.

Efficiency:
These algorithms are often very inefficient. They are very effective for small data but the amount of data mostly increase with time.

So, I am sharing a below code example to explain the linear search. I am using PHP in this case.

function linearSearch($arr, $searchableItems) {
    $totalItems  = count($arr);
    for ($i=0; $i<$totalItems; $i++) {
    	if ($arr[$i]===$searchableItems) {
    		echo $searchableItems .' found at Index '. $i .'.';
    	}
    }
    return false;
}

$arr = [1, 5, 6, 9, 11, 21, 25, 32, 36, 56, 68, 70, 79, 88, 91, 94, 100];

linearSearch($arr, 21);