📊 DSA Q24 / 28

What is the difference between linear search and binary search?

AI-Powered Answer ✓ Answered

Linear search and binary search are two fundamental algorithms used to find a target element within a collection of data. While both achieve the same goal, they differ significantly in their approach, efficiency, and prerequisites, making them suitable for different scenarios.

Linear Search

Linear search, also known as sequential search, is the simplest search algorithm. It sequentially checks each element of the list one by one from the beginning until a match is found or the end of the list is reached. It does not require the data to be sorted, making it versatile but generally less efficient for large datasets.

python
def linear_search(arr, target):
    for i in range(len(arr)):
        if arr[i] == target:
            return i  # Return the index if target is found
    return -1 # Return -1 if target is not found

Binary Search

Binary search is a more efficient algorithm for finding an element in a sorted list. It works by repeatedly dividing the search interval in half. It compares the target value with the middle element of the array. If they are not equal, the half in which the target cannot lie is eliminated, and the search continues on the remaining half, effectively halving the search space with each step.

python
def binary_search(arr, target):
    low = 0
    high = len(arr) - 1

    while low <= high:
        mid = (low + high) // 2
        if arr[mid] == target:
            return mid  # Return the index if target is found
        elif arr[mid] < target:
            low = mid + 1 # Search in the right half
        else:
            high = mid - 1 # Search in the left half
    return -1 # Return -1 if target is not found

Key Differences

FeatureLinear SearchBinary Search
PrerequisiteNo sorting requiredArray must be sorted
Time Complexity (Best)O(1) (Target is the first element)O(1) (Target is the middle element)
Time Complexity (Average)O(n)O(log n)
Time Complexity (Worst)O(n) (Target is last element or not present)O(log n) (Target is not present)
Space ComplexityO(1)O(1) (Iterative) or O(log n) (Recursive)
ApproachCompares each element sequentiallyDivides search space in half repeatedly
SuitabilitySmall, unsorted lists; when sorting is too costlyLarge, sorted lists; when efficiency is critical

In summary, while linear search is straightforward and suitable for any list, binary search offers significantly better performance for large datasets, provided the data is sorted. The choice between them depends on the specific requirements concerning data structure, size, and whether the data can be pre-sorted or is already sorted.