w3resource

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


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.

For more Practice: Solve these Related Problems:

  • Write a Java program to implement binary search on an array of custom objects using a Comparator to determine order.
  • Write a Java program to modify binary search to return the index of the first occurrence when duplicates exist.
  • Write a Java program to perform binary search on a rotated sorted array without restoring the original order.
  • Write a Java program to extend binary search to work on an array with missing values, returning the index of the closest match.

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.



Follow us on Facebook and Twitter for latest update.