Open In App

Searching Algorithms in Java

Last Updated : 10 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 Sequential Search in Java:
 

Java




// 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);
    }
}


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




// 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);
    }
}


Output: 

Element found at index 3

 

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

Iterative implementation of Binary Search

 

Java




// 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);
    }
}


Output: 

Element found at index 3

 

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



Similar Reads

Algorithms | Searching | Question 1
Linear search is also called------ (A) Random Search (B) Sequential search (C) Perfect search (D) None Answer: (B) Explanation: Linear Search is defined as a sequential search algorithm that starts at one end and goes through each element of a list until the desired element is found, otherwise, the search continues till the end of the data set. Hen
1 min read
Algorithms | Searching | Question 2
Which of the following is correct recurrence for worst case of Binary Search? (A) T(n) = 2T(n/2) + O(1) and T(1) = T(0) = O(1) (B) T(n) = T(n-1) + O(1) and T(1) = T(0) = O(1) (C) T(n) = T(n/2) + O(1) and T(1) = T(0) = O(1) (D) T(n) = T(n-2) + O(1) and T(1) = T(0) = O(1) Answer: (C) Explanation: Following is a typical implementation of Binary Search
2 min read
Algorithms | Searching | Question 3
Given a sorted array of integers, what can be the minimum worst-case time complexity to find ceiling of a number x in given array? The ceiling of an element x is the smallest element present in array which is greater than or equal to x. Ceiling is not present if x is greater than the maximum element present in array. For example, if the given array
2 min read
Algorithms | Searching | Question 4
Consider the following C program that attempts to locate an element x in an array Y[] using binary search. The program is erroneous. (GATE CS 2008) C/C++ Code 1. f(int Y[10], int x) { 2. int i, j, k; 3. i = 0; j = 9; 4. do { 5. k = (i + j) /2; 6. if( Y[k] On which of the following contents of Y and x does the program fail? (A) Y is [1 2 3 4 5 6 7 8
2 min read
Algorithms | Searching | Question 6
C/C++ Code , int x) { 2. int i, j, k; 3. i = 0; j = 9; 4. do { 5. k = (i + j) /2; 6. if( Y[k] In the above question, the correction needed in the program to make it work properly is (GATE CS 2008) (A) Change line 6 to: if (Y[k] &lt; x) i = k + 1; else j = k-1; (B) Change line 6 to: if (Y[k] &lt; x) i = k - 1; else j = k+1; (C) Change line 6 to: if
2 min read
Algorithms | Searching | Question 6
Which of the following is the correct recurrence for the worst case of Ternary Search? (A) T(n) = T(n/3) + 4, T(1) = 1 (B) T(n) = T(n/2) + 2, T(1) = 1 (C) T(n) = T(n + 2) + 2, T(1) = 1 (D) T(n) = T(n - 2) + 2, T(1) = 1 Answer: (A) Explanation: Following is a typical implementation of Binary Search. // A recursive ternary search function. It returns
2 min read
Difference between Searching and Sorting Algorithms
Prerequisite: Searching and Sorting Algorithms Searching Algorithms are designed to check for an element or retrieve an element from any data structure where it is used. Based on the type of operations these algorithms are generally classified into two categories: Sequential Search: The Sequential Search is the basic and simple Searching Algorithm.
4 min read
Searching Algorithms for 2D Arrays (Matrix)
Linear Search in 2D Array: Linear search is a simple and sequential searching algorithm. It is used to find whether a particular element is present in the array or not by traversing every element in the array. While searching in the 2D array is exactly the same but here all the cells need to be traversed In this way, any element is searched in a 2D
13 min read
Searching Algorithms
Searching algorithms are essential tools in computer science used to locate specific items within a collection of data. These algorithms are designed to efficiently navigate through data structures to find the desired information, making them fundamental in various applications such as databases, web search engines, and more. Table of Content What
5 min read
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. 1. Linear SearchLinear search is the simplest sea
6 min read