Algorithms Java

Implementing Binary Search Algorithm for Efficient Searching of Sorted Arrays

Reading Time: 2 mins

Introduction

Binary search is a search algorithm that works on sorted data. It operates by repeatedly dividing the search interval in half until the target value is found or the interval is empty. It’s a very efficient algorithm, with a runtime complexity of O(log n), where n is the number of elements in the array.

In this article, we’ll walk through how to implement binary search in Java to search for an integer in a sorted array.

Implementation

Let’s start by writing a method that performs a binary search. The method takes two arguments: an array of integers nums and an integer target that we’re searching for. The method returns the index of the target if it exists in the array, or -1 if it doesn’t.

public static int binarySearch(int[] nums, int target) {
    int left = 0;
    int right = nums.length - 1;

    while (left <= right) {
        int mid = left + (right - left) / 2;

        if (nums[mid] == target) {
            return mid;
        } else if (nums[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }

    return -1;
}

Here’s how the method works:

  • We start by setting left to the first index of the array, and right to the last index of the array.
  • We use a while loop to keep searching until the search interval is empty (left is greater than right), or we’ve found the target value.
  • In each iteration of the loop, we compute the midpoint of the search interval using the formula mid = left + (right - left) / 2. This avoids integer overflow errors that can occur if we use the simpler formula (left + right) / 2.
  • If the value at nums[mid] is equal to the target, we’ve found it, so we return mid.
  • If the value at nums[mid] is less than the target, we need to search the right half of the search interval, so we update left = mid + 1.
  • If the value at nums[mid] is greater than the target, we need to search the left half of the search interval, so we update right = mid - 1.

Example

Let’s look at an example of how to use the binarySearch method. Suppose we have the following array of integers:

int[] nums = {1, 3, 5, 7, 9};

We want to search for the value 5 in the array. We can call the binarySearch method like this:

int index = binarySearch(nums, 5);

The index variable will contain the value 2, which is the index of the value 5 in the array.

Conclusion

Binary search is a very efficient algorithm for searching sorted data. In this article, we’ve seen how to implement binary search in Java to search for an integer in a sorted array. We used a while loop to repeatedly divide the search interval in half, and we updated the search interval based on whether the target value was greater than or less than the midpoint value. By using this algorithm, we can search a large array in logarithmic time, which is much faster than linear search.

Related Posts

person in gray shirt holding a small paper with texts

Master Your Next Java Interview with These 50 Expert-Approved Questions and Answers

Reading Time: 12 minsJava is a popular programming language that is widely used in the development of enterprise applications, web applications, mobile applications, and more. As a result, Java developers are in high demand and a strong understanding of the language is essential for success in the field. In this article, we’ve compiled a list of the top 50 Java interview questions and answers to help you prepare for your next interview and ace it with confidence.

selective focus photography of gray metal padlock

Brute Force Algorithms: A Simple Approach to Problem-Solving

Reading Time: 4 minsBrute force algorithms are a class of problem-solving approaches that rely on a straightforward, repetitive approach to find a solution. While they can be slow and resource-intensive, they are simple to understand and implement and have a high probability of finding the correct solution. In this article, we will explore the basics of brute force algorithms and how to implement them in Java, from linear search to optimization problems.

Photo by Андрей Сизов

Exploring the World of Search Algorithms: A Comprehensive Overview

Reading Time: 6 minsSearch algorithms are used to find solutions to a wide range of problems, from navigating a maze to optimizing a business process. There are many different types of search algorithms, including breadth-first search, depth-first search, A* search, Dijkstra’s algorithm, binary search, and linear search. Other algorithms include jump search, interpolation search, exponential search, hashing, ternary search, Fibonacci search, Boyer-Moore search, Knuth-Morris-Pratt search, and heuristic search algorithms like genetic algorithms and simulated annealing. Each algorithm has its own set of characteristics and is suitable for different types of problems and scenarios. In this guide, we’ve provided a comprehensive overview of search algorithms to help you understand the different options available and how to choose the right algorithm for your needs.

Leave a Reply