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

How to implement the singleton pattern in JavaScript ES6+

Publish Date:2025/03/19 Views:54 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:76 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:115 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

How to implement the Command Design Pattern in Java

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

Hello everyone, today, we will learn an important design pattern which is often overlooked by Java developers. Yes, I am talking about the Command pattern which helps us write flexible and loosely coupled code to implement actions and event

How to use the State Design Pattern in Java?

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

The State design pattern is a behavioral pattern. The State pattern looks similar to the Strategy pattern, but it helps in managing the object states so that they behave differently in different states. In this example, we will take a famou

Adapter vs Decorator vs Facade vs Proxy Design Pattern in Java

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

There are some striking similarities between the Adapter, Decorator, Facade, and Proxy design patterns as they all use composition and delegation to solve problems. The Adapter pattern wraps an interface and delegates calls to it. Decorator

Observer Design Pattern in Java

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

Observer design pattern in Java is a basic core Java pattern where the Observer monitors any changes in the state or properties of the Subject . For example, a company updates all shareholders about any decision taken by them here the compa

How to use Composite Design Pattern in Java?

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

Hello Java programmers, if you want to learn about Composite Design Pattern in Java , such as how to implement Composite Design Pattern and when to use it, then you have come to the right place. In this article, we will discuss Composite De

How to find the IP address of the local host in Java

Publish Date:2025/03/17 Views:98 Category:NETWORK

The Java Networking API provides a way to find the local host IP address from a Java program using the java.net InetAddress class. It is rare that you need the local host IP address in a Java program. Most of the time, I use the Unix command to find t

Scan to Read All Tech Tutorials

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

Recommended

Tags

Scan the Code
Easier Access Tutorial