Java: 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:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/java-exercises/search/java-search-exercise-1.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics