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:

Below is the implementation of the Sequential Search in Java:

Java

// Java program to implement Linear Search // 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) // Driver Code public static void main(String args[]) // Element to search // Function Call int result = search(arr, x); if (result == - 1 ) System.out.print( "Element is not present in array" ); System.out.print( "Element is present" 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