Week 3 Discussion Forum

How linear search works?

How linear search works?

by Zafrin All Mustary -
Number of replies: 0

A linear search will sequentially iterate over every n value in a list until the index reaches the maximum one inputted and normally it will iterate over every element until it reaches the last one in the list if the target value is not in the list, O(n).

A basic example of a linear search

int a[3] = { 0, 2, 1 };

for (int i = 0; i < sizeof(a); i++){  

    if (a[i] == 1)

    break;

}

To explain, a is a list of 3 elements, then we perform a for loop that iterates over every element in a if the target value “1” is found, then the loop will break (it exits the loop). However, this is an example of where it is the worst case scenario because the target value is at the end of the list, and as we go further in the list, we’re wasting more time.


148 words