JIYIK CN >

Current Location:Home > Learning > ALGORITHM >

How to implement binary search in Java without recursion?

Author:JIYIK Last Updated:2025/03/19 Views:

Hey Java programmers, if you want to implement binary search in Java and looking for iterative and recursive binary search algorithms, then you have come to the right place. Today I am going to teach you an important algorithm. In computer science, binary search or semi-interval search is a divide and conquer algorithm that locates the position of an item in a sorted array. Binary search works by comparing the input value with the middle element of the array. The comparison determines whether the element is equal to the input, less than the input, or greater than the input.

When the compared element is equal to the input, the search stops and the position of the element is usually returned. If the element is not equal to the input, a comparison is performed to determine whether the input is less than or greater than the element.

Depending on what algorithm it is it then starts over but only searches the top or bottom subset of the array elements. If the input is not in the array the algorithm will usually output a unique value to indicate this.

A binary search algorithm typically halves the number of items to be examined with each successive iteration, thereby locating a given item (or determining its absence) in logarithmic time.

Binary search is a divide and conquer search algorithm. It works by splitting the input set into two halves and then applying the algorithm and repeating the same steps until the work is done.

Binary Search vs. Linear Search Runtime Grokking Algorithm

Java Binary Search Without Recursion It is also very intuitive and full of helpful diagrams that explain the concepts very well. For example, in the diagram above, we can see that linear search gets slower and slower as the number of elements increases, but binary search does not. For example, with 4 billion items, binary search only needs 32 guesses


Binary Search Example in Java without Recursion

The algorithm is implemented recursively. Also, an interesting fact about binary search implementation in Java is that Joshua Blochjava.util.Arrays , the author of the famous Effective Java book , implemented binary search in .

import java.util.Arrays;

/**
 * 实现二进制搜索的 Java 程序。
 */
public class Main {
    public static void main(String args[]) {
        int[] list = new int[]{23, 43, 31, 12};
        int number = 12;
        Arrays.sort(list);
        System.out.printf("Binary Search %d in integer array %s %n", number, Arrays.toString(list));
        binarySearch(list, 12);
        System.out.printf("Binary Search %d in integer array %s %n", 43, Arrays.toString(list));
        binarySearch(list, 43);
        list = new int[]{123, 243, 331, 1298};
        number = 331;
        Arrays.sort(list);
        System.out.printf("Binary Search %d in integer array %s %n", number, Arrays.toString(list));
        binarySearch(list, 331);
        System.out.printf("Binary Search %d in integer array %s %n", 331, Arrays.toString(list));
        binarySearch(list, 1333);
        Arrays.sort(list);
        int index = Arrays.binarySearch(list, 3);
    }

    /**
     * 在 Java 中的排序数组中执行二分搜索
     * @param input
     * @param number
     * @return 元素在数组中的位置
     */
    public static void binarySearch(int[] input, int number) {
        int first = 0;
        int last = input.length - 1;
        int middle = (first + last) / 2;
        while (first <= last) {
            if ( input[middle] < number){
                first = middle + 1;
            } else if (input[middle] == number) {
                System.out.printf(number + " found at location %d %n", middle);
                break;
            } else {
                last = middle - 1;
            }
            middle = (first + last) / 2;
        } if ( first > last){
            System.out.println(number + " is not present in the list.\n");
        }
    }
}

The execution results are as follows

Implementing binary search results in Java without recursion

That's all about how to implement a binary search algorithm in Java without recursion. As with any recursive algorithm, this code does not use any loops like while, , foror do-while. Ideally, we wouldn't need to write code for binary search for day-to-day tasks because the Java library already has a , binarySearch(), or . But knowing how to write these algorithms helps in interviews.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Store Div Id in PHP variable and pass it to JavaScript

Publish Date:2025/04/13 Views:51 Category:PHP

This article shows you how to div id store a in a PHP variable and pass it to JavaScript code. We will answer the following questions. What is div id ? How to div id store in a PHP variable? How to pass variables to JavaScript code? Let’s

Design Patterns in Java - Visitor Pattern

Publish Date:2025/03/19 Views:175 Category:ALGORITHM

Today, we are going to learn one of the most useful patterns, the Visitor Pattern. What is the Visitor pattern? Well, let's look at an example. Let's say you're a software engineer working at a university. The university rarely has establis

How to use Strategy Pattern in Java?

Publish Date:2025/03/19 Views:142 Category:ALGORITHM

Hi everyone, you might have heard, “Can you tell me about any design pattern other than Singleton design pattern that you have used recently in your project?”. This is one of the popular questions in various Java interviews in recent ye

Difference between Proxy Mode and State Mode in Java

Publish Date:2025/03/19 Views:76 Category:ALGORITHM

Hi guys, if you are preparing for Java interview and looking for difference between Proxy and State design pattern, then you are at the right place. In the past, I have explained several important object-oriented design patterns like State,

Strategy Design Pattern and Open-Closed Principle in Java

Publish Date:2025/03/19 Views:114 Category:ALGORITHM

The Strategy design pattern is based on the Open/Closed design principle , the famous " O SOLID " of design principles . It is one of the patterns that has become popular in the field of object-oriented analysis and design, along with the D

How to implement the singleton pattern in JavaScript ES6+

Publish Date:2025/03/19 Views:55 Category:ALGORITHM

In this article, we will show you how to implement the singleton pattern in JavaScript. If we are a full-stack JavaScript developer, we know that JavaScript is a powerful language and we can build amazing websites with it. On the other hand

How to use the Adapter design pattern in Java

Publish Date:2025/03/19 Views:77 Category:ALGORITHM

The Adapter design pattern in Java , also known as the Wrapper pattern, is another very useful GOF pattern that helps bridge the gap between two classes in Java. According to the Gang of Four pattern list, Adapter is a structural pattern, m

Java Decorator Design Pattern Example

Publish Date:2025/03/19 Views:116 Category:ALGORITHM

Hello everyone, if you want to learn about Decorator Design Pattern in Java , then you have come to the right place. As design patterns are very important while building software and equally important in any core Java interview, it is alway

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial