Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Searching Algorithms
  • MCQs on Searching Algorithms
  • Tutorial on Searching Algorithms
  • Linear Search
  • Binary Search
  • Ternary Search
  • Jump Search
  • Sentinel Linear Search
  • Interpolation Search
  • Exponential Search
  • Fibonacci Search
  • Ubiquitous Binary Search
  • Linear Search Vs Binary Search
  • Interpolation Search Vs Binary Search
  • Binary Search Vs Ternary Search
  • Sentinel Linear Search Vs Linear Search
Open In App
Next Article:
Fastest Searching Algorithm | GFact
Next article icon

Searching Algorithms in Java

Last Updated : 10 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
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)



Next Article
Fastest Searching Algorithm | GFact

D

divyanshusharmaiot18
Improve
Article Tags :
  • DSA
  • Java
  • Searching
  • Algorithms-Searching
  • Binary Search
Practice Tags :
  • Binary Search
  • Java
  • Searching

Similar Reads

  • Searching Algorithms
    Searching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
    3 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.
    6 min read
  • Fastest Searching Algorithm | GFact
    Pattern searching is a critical operation in the field of computer science, Its applications range from text processing and DNA sequencing to image recognition and data mining. As data sizes grow exponentially, the demand for faster pattern-searching algorithms has only grown. Which is the Fastest S
    2 min read
  • What is Binary Search Algorithm?
    Binary Search is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half and the correct interval to find is decided based on the searched value and the mid value of the interval. Properties of Binary Search:Binary search is performed on the sorted data struct
    1 min read
  • Searching in Array
    Searching is one of the most common operations performed in an array. Array searching can be defined as the operation of finding a particular element or a group of elements in the array. There are several searching algorithms. The most commonly used among them are: Linear Search Binary Search Ternar
    4 min read
  • Boyer Moore Algorithm for Pattern Searching
    Pattern searching is an important problem in computer science. When we do search for a string in a notepad/word file, 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] wh
    15+ min read
  • Applications of String Matching Algorithms
    String matching is a process of finding a smaller string inside a larger text. For example, searching for the word "apple" in a paragraph. It is useful in areas like text search, data analysis and more. There are two types of string matching algorithms: Exact String Matching AlgorithmsApproximate St
    2 min read
  • Compare two Strings in Java
    String in Java are immutable sequences of characters. Comparing strings is the most common task in different scenarios such as input validation or searching algorithms. In this article, we will learn multiple ways to compare two strings in Java with simple examples. Example: To compare two strings i
    4 min read
  • Pattern Searching
    Pattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Important Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works in O(m x n) time
    2 min read
  • Searching and Sorting Algorithm Notes for GATE Exam [2024]
    As you gear up for the GATE Exam 2024, it's time to dive into the world of searching and sorting algorithms. Think of these algorithms as the super-smart tools that help computers find stuff quickly and organize data neatly. These notes are here to guide you through the ins and outs of these algorit
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences