Search Algorithm Visualization

Range: 20-350

Choose a Search Algorithm

Element Found at: -
Steps Taken: 0

Algorithm Documentation

Implementation in Java

// Java code for linearly searching x in arr[]
// If x is present then return its location, otherwise return -1

class LinearSearch {
    public static int search(int arr[], int x) {
        int N = arr.length;
        for (int i = 0; i < N; i++) {
            if (arr[i] == x)
                return i;
        }
        return -1;
    }

    // Driver's code
    public static void main(String args[]) {
        int arr[] = { 2, 3, 4, 10, 40 };
        int x = 10;

        // Function call
        int result = search(arr, x);
        if (result == -1)
            System.out.print("Element is not present in array");
        else
            System.out.print("Element is present at index " + result);
    }
}
// Java program for implementation of Binary Search
class BinarySearch {
    // Returns index of x if it is present in arr[l..r], else return -1
    int binarySearch(int arr[], int l, int r, int x) {
        if (r >= l) {
            int mid = l + (r - l) / 2;
            
            // If the element is present at the middle itself
            if (arr[mid] == x)
                return mid;
            
            // If element is smaller than mid, then it can only be present in left subarray
            if (arr[mid] > x)
                return binarySearch(arr, l, mid - 1, x);
            
            // Else the element can only be present in right subarray
            return binarySearch(arr, mid + 1, r, x);
        }
        
        // We reach here when element is not present in array
        return -1;
    }
    
    // Driver method to test above
    public static void main(String args[]) {
        BinarySearch ob = new BinarySearch();
        int arr[] = { 2, 3, 4, 10, 40 };
        int n = arr.length;
        int x = 10;
        int result = ob.binarySearch(arr, 0, n - 1, x);
        if (result == -1)
            System.out.println("Element not present");
        else
            System.out.println("Element found at index " + result);
    }
}

Time Complexity

Linear Search:
O(n) Best: O(1), Worst: O(n), Average: O(n)
Binary Search:
O(log n) Best: O(1), Worst: O(log n), Average: O(log n)

Space Complexity

Linear Search: O(1)
Binary Search: O(1) iterative, O(log n) recursive

Key Differences

Linear Search: Works on unsorted arrays, simple implementation
Binary Search: Requires sorted array, much faster for large datasets