The Wayback Machine - https://web.archive.org/web/20240827225521/https://www.geeksforgeeks.org/java-program-for-binary-search-recursive-and-iterative/
Open In App

Java Program for Binary Search (Recursive and Iterative)

Last Updated : 13 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

So as we all know binary search is one of the searching algorithms that is most frequently applied while dealing with data structures where the eccentric goal is not to traverse the whole array. Here array must be sorted as we check the middle element and ignore the half of the array which is of no use as per the number system. We basically ignore half of the elements just after one comparison. So do we keep on iterating till the element is found or land upon a conclusion that element is not present n the array.

Algorithms:

  1. Compare x with the middle element.
  2. If x matches with the 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 the right half.
  4. Else (x is smaller) recur for the left half.

Example 1 

Java




// Java Program to Illustrate
// Iterative Binary Search
 
// Main class
// BinarySearch
class GFG {
 
    // Method 1
    // 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;
 
        // Checking element in whole array
        while (l <= r) {
            int m = l + (r - l) / 2;
 
            // Check if x is present at mid
            if (arr[m] == x)
                return m;
 
            // If x greater, ignore left half
            if (arr[m] < x)
                l = m + 1;
 
            // If x is smaller,
            // element is on left side
            // so ignore right half
            else
                r = m - 1;
        }
 
        // If we reach here,
        // element is not present
        return -1;
    }
 
    // Method 2
    // Main driver method
    public static void main(String args[])
    {
 
        GFG ob = new GFG();
 
        // Input array
        int arr[] = { 2, 3, 4, 10, 40 };
        // Length of array
        int n = arr.length;
        // Element to be checked if present or not
        int x = 10;
 
        // Calling the method 1 and
        // storing result
        int result = ob.binarySearch(arr, x);
 
        // Element present
        if (result == -1)
 
            // Print statement
            System.out.println("Element not present");
 
        // Element not present
        else
 
            // Print statement
            System.out.println("Element found at index "
                               + result);
    }
}


Output

Element found at index 3

Time Complexity: O(log n)

Auxiliary Space: O(1)
 

Example 2 

Java




// Java Program to Illustrate Recursive Binary Search
 
// Importing required classes
import java.util.*;
 
// Main class
class GFG {
 
    // Method 1
    // Recursive binary search
    // 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)
    {
        // Restrict the boundary of right index
        // and the left index to prevent
        // overflow of indices
        if (r >= l && l <= arr.length - 1) {
 
            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;
    }
 
    // Method 2
    // Main driver method
    public static void main(String args[])
    {
 
        // Creating object of above class
        GFG ob = new GFG();
 
        // Custom input array
        int arr[] = { 2, 3, 4, 10, 40 };
 
        // Length of array
        int n = arr.length;
 
        // Custom element to be checked
        // whether present or not
        int x = 10;
 
        // Calling above method
        int result = ob.binarySearch(arr, 0, n - 1, x);
 
        // Element present
        if (result == -1)
 
            // Print statement
            System.out.println("Element not present");
 
        // Element not present
        else
 
            // Print statement
            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

Java Program to Search ArrayList Element Using Binary Search
Linear Search can be implemented for sorting and non-sorting elements of a Data structure particular Data structure but the average case time complexity is O(n). Whereas as Binary Search can be implemented only when the items are in sorted order and average-case time complexity is O(logn) and both Transversal have best-case Time complexity is O(1).
3 min read
Java Program to Search User Defined Object From a List By Using Binary Search Using Comparator
The Comparator interface in Java can be used to compare user-defined objects. The Comparator interface is present in java.util package. Binary search is a searching algorithm that uses the divide and conquers rule to search the presence of an element in a list or array. The binary search algorithm works only on a sorted list. In case the list is no
6 min read
Java Program for Anagram Substring Search (Or Search for all permutations)
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] and its permutations (or anagrams) in txt[]. You may assume that n &gt; m. Expected time complexity is O(n) Examples: 1) Input: txt[] = "BACDGABCDA" pat[] = "ABCD" Output: Found at Index 0 Found at Index 5 Found a
4 min read
Java Program for Iterative Merge Sort
Following is a typical recursive implementation of Merge Sort that uses last element as pivot. Java Code // Recursive Java Program for merge sort import java.util.Arrays; public class GFG { public static void mergeSort(int[] array) { if(array == null) { return; } if(array.length &amp;gt; 1) { int mid = array.length / 2; // Split left part int[] lef
2 min read
Java Program to Add Two Matrix Using Iterative Approach
Given two matrices A and B, Add two matrices using iterative approaches in Java, like for loop, while loop, do-while loop. For the addition of two matrices, the necessary condition is that both the matrices must have the same size, and addition must take complete iteration to both the matrices. Examples Input: A[][] = {{1, 3}, {2, 4}} B[][] = {{1,
2 min read
Java Program for Iterative Quick Sort
Below is the implementation of Iterative Quick Sort: [GFGTABS] Java // Java implementation of iterative quick sort import java.io.*; public class IterativeQuickSort { void swap(int arr[], int i, int j) { int t = arr[i]; arr[i] = arr[j]; arr[j] = t; } /* This function is same in both iterative and recursive*/ int partition(int arr[], int l, int h) {
3 min read
Java Program for Recursive Bubble Sort
Background :Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.Following is iterative Bubble sort algorithm : // Iterative Bubble Sort bubbleSort(arr[], n) { for (i = 0; i &lt; n-1; i++) // Last i elements are already in place for (j = 0; j arr[j+1]) swap(arr[j], arr[j+1]
2 min read
Java Program for Recursive Insertion Sort
Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands.Below is an iterative algorithm for insertion sort Algorithm // Sort an arr[] of size n insertionSort(arr, n) Loop from i = 1 to n-1. a) Pick element arr[i] and insert it into sorted sequence arr[0..i-1] Java Code // Recursive Java program for inserti
2 min read
Java Program For Recursive Selection Sort For Singly Linked List - Swapping Node Links
Given a singly linked list containing n nodes. The problem is to sort the list using the recursive selection sort technique. The approach should be such that it involves swapping node links instead of swapping node data. Examples: Input: 10 -&gt; 12 -&gt; 8 -&gt; 4 -&gt; 6 Output: 4 -&gt; 6 -&gt; 8 -&gt; 10 -&gt; 12 In Selection Sort, we first find
4 min read
Java Program to Perform Binary Search on ArrayList
The ArrayList class is a part of the collection framework and is present in java.util package. It provides us with resizable or dynamic arrays in java. It is quite slower than standard arrays but can be helpful in some programs where we need to come up with cleaner and shorter code and lots of manipulation of an array is needed. The most effective
6 min read
Java Program to Find the Cube Root of a Given Number Using Binary Search
Given a non-negative number find the cube root of a number using the binary search approach. Examples : Input: x = 27 Output: 3 Explanation: The cube root of 16 is 4. Input: x = 120 Output: 4 Explanation: The cube root of 120 lies in between 4 and 5 so floor of the cube root is 4.Naive Approach: Check the cube of every element till n and store the
2 min read
Java program to Find the Square Root of a Number using Binary Search
Given a non-negative number find the square root of a number using the binary search approach. Examples : Input: x = 16 Output: 4 Explanation: The square root of 16 is 4. Input: x = 5 Output: 2 Explanation: The square root of 5 lies in between 2 and 3 so floor of the square root is 2. Naive Approach: Check the square of every element till n and sto
3 min read
Binary Search on Java Vector
Vector is a legacy class in Java and is present from Java 1.2 version. It implements the List interface of the Collection framework and is found in java.util package. Vector is just like an array that can grow dynamically. Vectors are synchronized ie vectors are thread-safe. Vectors are mainly used where thread synchronization is of utmost importan
3 min read
Java Program for Search an element in a sorted and rotated array
An element in a sorted array can be found in O(log n) time via binary search. But suppose we rotate an ascending order sorted array at some pivot unknown to you beforehand. So for instance, 1 2 3 4 5 might become 3 4 5 1 2. Devise a way to find an element in the rotated array in O(log n) time. Example: Input : arr[] = {5, 6, 7, 8, 9, 10, 1, 2, 3};
9 min read
Iterative Postorder Traversal of N-ary Tree
Given an N-ary tree, the task is to find the post-order traversal of the given tree iteratively.Examples: Input: 1 / | \ 3 2 4 / \ 5 6 Output: [5, 6, 3, 2, 4, 1] Input: 1 / \ 2 3 Output: [2, 3, 1] Approach:We have already discussed iterative post-order traversal of binary tree using one stack. We will extend that approach for the n-ary tree. The id
10 min read
Java Program to Search for a File in a Directory
Searching files in Java can be performed using the File class and FilenameFilter interface. The FilenameFilter interface is used to filter files from the list of files. This interface has a method boolean accept(File dir, String name) that is implemented to find the desired files from the list returned by the java.io.File.list() method. This method
3 min read
Java Program to Search an Element in a Linked List
Prerequisite: LinkedList in java LinkedList is a linear data structure where the elements are not stored in contiguous memory locations. Every element is a separate object known as a node with a data part and an address part. The elements are linked using pointers or references. Linked Lists are preferred over arrays in case of deletions and insert
5 min read
Java Program to Search an Element in a Circular Linked List
A linked list is a kind of linear data structure where each node has a data part and an address part which points to the next node. A circular linked list is a type of linked list where the last node points to the first one, making a circle of nodes. Example: Input : CList = 6-&gt;5-&gt;4-&gt;3-&gt;2, find = 3 Output: Element is present Input : CLi
3 min read
Java Program to Search the Contents of a Table in JDBC
In order to deal with JDBC standard 7 steps are supposed to be followed: Import the databaseLoad and register driversCreate a connectionCreate a statementExecute the queryProcess the resultsClose the connectionProcedure: Import the database-syntax for importing the sql database in java is- import java.sql.* ;Load and register drivers-syntax for reg
5 min read
Java Program to Implement the String Search Algorithm for Short Text Sizes
Pattern searching is a crucial problem in computer science. When we do search for a string in notepad/word file or browser or database, pattern searching algorithms are used to show the search results. A typical problem statement would be-Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints
4 min read
Java Program To Recursively Linearly Search An Element In An Array
Given an array arr[] of n elements, write a function to recursively search a given element x in arr[]. Illustration: Input : arr[] = {25, 60, 18, 3, 10} Output : Element to be searched : 3 Input : arr[] = {10,20,30,24,15,40} Output : -1 For x = 35 Element x is not present in arr[] Procedure: The idea is to search the element from both the sides of
3 min read
Java Program for Linear Search
Given an array arr[] of n elements, write a function to search a given element x in arr[]. ALGORITHM for Linear SearchStep 1: Start Step 2: Declare an array and search element as key.Step 3: Traverse the array until the number is found.Step 4: If the key element is found, return the index position of the array elementStep 5: If the key element is n
3 min read
Java Program to Search a Particular Word in a String Using Regex
In Java string manipulation, searching for specific words is a fundamental task. Regular expressions (regex) offer a powerful and flexible approach to achieve this search. It matches the patterns simply by comparing substrings. In this article, we will learn how to search for a particular word in a string using regex in Java. Regular Expressions:Pa
3 min read
Java Program for Breadth First Search or BFS for a Graph
The Breadth First Search (BFS) algorithm is used to search a graph data structure for a node that meets a set of criteria. It starts at the root of the graph and visits all nodes at the current depth level before moving on to the nodes at the next depth level. Relation between BFS for Graph and Tree TraversalBreadth-First Traversal (or Search) for
3 min read
Java Program for Depth First Search or DFS for a Graph
Depth First Traversal (or DFS) for a graph is similar to Depth First Traversal of a tree. Prerequisite: Graph knowledge is important to understand the concept of DFS. What is DFS?DFS or Depth First Traversal is the traversing algorithm. DFS can be used to approach the elements of a Graph. To avoid processing a node more than once, use a boolean vis
3 min read
Java Program to Search an Element in Vector
A vector in Java is a dynamic array that can be resized as needed. It is synchronized, which means it is safe in multi-threaded programs. To find an element in a Vector we have to loop through its elements to find a match. In this article, we will learn how to search for a component in a Vector using Java. Methods to Search an Element in VectorUsin
3 min read
Check if an array is sorted and rotated using Binary Search
Pre-requisite: Check if an array is sorted and rotated using Linear SearchGiven an array arr[] of N distinct integers, the task is to check if this array is sorted when rotated counter-clockwise. A sorted array is not considered sorted and rotated, i.e., there should at least one rotation. Examples: Input: arr[] = { 3, 4, 5, 1, 2 } Output: true Exp
11 min read
Java Program to Calculate the Difference Between the Sum of the Odd Level and the Even Level Nodes of a Binary Tree
Graph Traversal using DFS is an obvious way to traverse a tree with recursion. Below is an algorithm for traversing binary tree using DFS. Prerequisites Graph Traversal using DFSJava Basics(Array List)Recursion Basics Algorithm Initialize the current node as root node and the parent as -1.Traverse the Binary Tree as the in the general DFS fashion a
2 min read
Java Program to Find Maximum number of 0s placed consecutively at the start and end in any rotation of a Binary String
Given a binary string S of size N, the task is to maximize the sum of the count of consecutive 0s present at the start and end of any of the rotations of the given string S. Examples: Input: S = "1001"Output: 2Explanation:All possible rotations of the string are:"1001": Count of 0s at the start = 0; at the end = 0. Sum= 0 + 0 = 0."0011": Count of 0
6 min read
Java Program to Check horizontal and vertical symmetry in binary matrix
Given a 2D binary matrix of N rows and M columns. The task is to check whether the matrix is horizontally symmetric, vertically symmetric, or both. The matrix is said to be horizontally symmetric if the first row is the same as the last row, the second row is the same as the second last row, and so on. And the matrix is said to be vertically symmet
4 min read
Article Tags :