Searching Algorithms in Java

Searching Algorithms are designed to check for an element or retrieve an element from any data structure where it is stored. Based on the type of search operation, these algorithms are generally classified into two categories:

  1. Sequential Search: In this, the list or array is traversed sequentially and every element is checked. For Example: Linear Search.
  2. Interval Search: These algorithms are specifically designed for searching in sorted data-structures. These type of searching algorithms are much more efficient than Linear Search as they repeatedly target the center of the search structure and divide the search space in half. For Example: Binary Search.

Linear Search: The idea is to traverse the given array arr[] and find the index at which the element is present. Below are the steps:

  • Let the element to be search be x.
  • Start from the leftmost element of arr[] and one by one compare x with each element of arr[].
  • If x matches with an element then return that index.
  • If x doesn’t match with any of elements then return -1.

Below is the implementation of the Sequencial Search in Java:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement Linear Search
  
class GFG {
  
    // Function for linear search
    public static int search(int arr[], int x)
    {
        int n = arr.length;
  
        // Traverse array arr[]
        for (int i = 0; i < n; i++) {
  
            // If element found then
            // return that index
            if (arr[i] == x)
                return i;
        }
        return -1;
    }
  
    // Driver Code
    public static void main(String args[])
    {
        // Given arr[]
        int arr[] = { 2, 3, 4, 10, 40 };
  
        // Element to search
        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);
    }
}

chevron_right


Output:

Element is present at index 3


Time Complexity: O(N)
Auxiliary Space: O(1)



Binary Search: This algorithm search element in a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or the interval is empty. Below are the steps:

  1. Compare x with the middle element.
  2. If x matches with middle element, we return the mid index.
  3. Else If x is greater than the mid element, then x can only lie in the right half subarray after the mid element. So we recur for right half.
  4. Else (x is smaller) recur for the left half.

Recursive implementation of Binary Search

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of recursive
// Binary Search
  
class BinarySearch {
  
    // Function that returns index of
    // x if it is present in arr[l, r]
    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);
        }
  
        // Reach here when element is
        // not present in array
        return -1;
    }
  
    // Driver Code
    public static void main(String args[])
    {
  
        // Create object of this class
        BinarySearch ob = new BinarySearch();
  
        // Given array arr[]
        int arr[] = { 2, 3, 4, 10, 40 };
        int n = arr.length;
        int x = 10;
  
        // Function Call
        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);
    }
}

chevron_right


Output:

Element found at index 3


Time Complexity: O(N*log N)
Auxiliary Space: O(1)

Iterative implementation of Binary Search

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of iterative
// Binary Search
  
class BinarySearch {
  
    // Returns index of x if it is present
    // in arr[], else return -1
    int binarySearch(int arr[], int x)
    {
  
        int l = 0, r = arr.length - 1;
  
        // Iterate until l <= r
        while (l <= r) {
            int m = l + (r - l) / 2;
  
            // Check if x is at mid
            if (arr[m] == x)
                return m;
  
            // If x greater than arr[m]
            // then ignore left half
            if (arr[m] < x)
                l = m + 1;
  
            // If x is smaller than arr[m]
            // ignore right half
            else
                r = m - 1;
        }
  
        // If we reach here, then element
        // was not present
        return -1;
    }
  
    // Driver Code
    public static void main(String args[])
    {
  
        // Create object of this class
        BinarySearch ob = new BinarySearch();
  
        // Given array arr[]
        int arr[] = { 2, 3, 4, 10, 40 };
        int n = arr.length;
        int x = 10;
  
        // Function Call
        int result = ob.binarySearch(arr, x);
  
        if (result == -1)
            System.out.println("Element not present");
        else
            System.out.println("Element found at index "
                               + result);
    }
}

chevron_right


Output:

Element found at index 3


Time Complexity: O(N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.