Binary Search in Java - Explained
You are looking for an explanation of how binary search works in Java ? If so, then search no more!
What is Binary search?
In Java programming language, binary search is an advanced searching algorithm used to search through a single or multiple arrays for a search element.
How does the binary search algorithm works?
In binary search, the array has to be sorted first. In this method, when the user searches for a value, the number of elements to be searched is reduced, because it locates the middle number and then either moves to the upper half or the lower half to continue the search.
Program for Binary Search
Suppose I have to search for a number and return its position (index) in the array.
int arr[] = {5,10,15,20,25,30,35,40,45,50}
For example if I search for say, 35
The program has been given below for binary search:
Points to Note:
- Binary search only works with an array already sorted
- This is effective for very large arrays, however not recommended for small array
Comments
Post a Comment