Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Java Exercises: Find a specified element in a given array of elements using Binary Search

Java Search: Exercise-1 with Solution

Write a Java program to find a specified element in a given array of elements using Binary Search.

Sample Solution:

Java Code:

public class Main {
     public static int binarySearch(int[] nums, int flag) {
        int hi_num = nums.length - 1;
        int lo_num = 0;
        while (hi_num >= lo_num) {
            int guess = (lo_num + hi_num) >>> 1;   
            if (nums[guess] > flag) {
                hi_num = guess - 1;
            } else if (nums[guess] < flag) {
                lo_num = guess + 1;
            } else {
                return guess;
            }
        }
        return -1;
    }
 
    public static void main(String[] args) {
        int[] nums = {1, 5, 6, 7, 8, 11};
        int search_num = 7;
        int index = binarySearch(nums, search_num);
        if (index == -1) {
            System.out.println(search_num + " is not in the array");
        } else {
            System.out.println(search_num + " is at index " + index);
        }
    }
}

Sample Output:

7 is at index 3

Flowchart:

Flowchart: Find a specified element in a given array of elements using Binary Search.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Java Search Exercises.
Next: Write a Java program to find a specified element in a given array of elements using Linear Search.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe