Linear Search

Linear search is the simplest searching algorithm. It sequentially checks each element of the list until it finds the target value.

Steps:

  • Start from the first element of the list.
  • Compare each element of the list with the target value.
  • If the element matches the target value, return its index.
  • If the target value is not found after iterating through the entire list, return -1.

Implementation of Linear Search in Python:

Python
def linear_search(arr, target):
    """
    Perform linear search to find the target value in the given list.

    Parameters:
        arr (list): The list to be searched.
        target: The value to be searched for.

    Returns:
        int: The index of the target value if found, otherwise -1.
    """
    for i in range(len(arr)):
        if arr[i] == target:
            return i
    return -1

# Example usage:
arr = [2, 3, 4, 10, 40]
target = 10
result = linear_search(arr, target)
if result != -1:
    print(f"Linear Search: Element found at index {result}")
else:
    print("Linear Search: Element not found")

Output
Linear Search: Element found at index 3


Searching Algorithms in Python

Searching algorithms are fundamental techniques used to find an element or a value within a collection of data. In this tutorial, we’ll explore some of the most commonly used searching algorithms in Python. These algorithms include Linear Search, Binary Search, Interpolation Search, and Jump Search.

Similar Reads

1. Linear Search

Linear search is the simplest searching algorithm. It sequentially checks each element of the list until it finds the target value....

2. Binary Search

Binary search is a more efficient searching algorithm suitable for sorted lists. It repeatedly divides the search interval in half until the target value is found....

3. Interpolation Search

Interpolation search is an improved version of binary search, especially suitable for large and uniformly distributed arrays. It calculates the probable position of the target value based on the value of the key and the range of the search space....

4. Jump Search

Jump search is another searching algorithm suitable for sorted arrays. It jumps ahead by a fixed number of steps and then performs a linear search in the smaller range....

Conclusion

In this tutorial, we’ve covered four fundamental searching algorithms in Python: Linear Search, Binary Search, Interpolation Search, and Jump Search. Each algorithm has its advantages and is suitable for different scenarios. Understanding these algorithms and their implementations will help you effectively search for elements within a collection of data....