6/recent/ticker-posts

Linear Search Algorithm



Linear search is a simple searching algorithm that sequentially checks each element in a list or array until a match is found or the end of the list is reached. It is also known as a sequential search.

Algorithm:

  1. Start at the beginning of the list or array.
  2. Compare the target value with the current element.
  3. If the current element matches the target value, return the index of the current element and exit.
  4. If the end of the list is reached without finding a match, return a “not found” indicator.
  5. If a match is not found, move to the next element in the list and repeat steps 2–4.
  6. Continue the process until a match is found or the end of the list is reached.

Example:

Finding 27 in the Array [8, 15, 45, 3, 9, 27, 90, 84]

Step 1:

Step 2:

Step 3:

Step 4:


Step 5 :

Step 6 :

Since the current element (27) matches the target value, the linear search algorithm stops and returns the index of the current element, which is 5.

Therefore, the linear search algorithm will return the index 5 for the element 27 in this example.

Code:

Here’s an example implementation of the linear search algorithm in Python:

def linear_search(array, target):
for i in range(len(array)):
if array[i] == target:
return i
return -1
array = [8, 15, 45, 3, 9, 27, 90, 84]
target = 27
result = linear_search(array, target)
if result != -1:
print(f"Element {target} found at index {result}.")
else:
print(f"Element {target} not found.")

Output:

Element 27 found at index 5.

Time Complexity:

The time complexity of the linear search algorithm is O(n) in the worst case, where n is the number of elements in the array. This is because, in the worst case scenario, the algorithm may need to iterate through the entire array to find the target element or determine that it is not present.

Usage:

Linear search is suitable when the data set is small, or when efficiency is not a major concern. It is a simple algorithm to implement and understand.

follow my Instagram account :

https://www.instagram.com/nature.pulse_/

Conclusion:

Linear search is a basic and straightforward algorithm for searching an element in a list or array. While it may not be the most efficient for large or sorted data sets, it can be useful in simple scenarios or when the data set is small.

Post a Comment

0 Comments