- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to implement binary search
Binary search is a fast search algorithm with run-time complexity of Ο(log n). This search algorithm works on the principle of divide and conquer. For this algorithm to work properly, the data collection should be in the sorted form.
The binary search looks for a particular item by comparing the middle most item of the collection. If a match occurs, then the index of the item is returned. If the middle item is greater than the item, then the item is searched in the sub-array to the left of the middle item. Otherwise, the item is searched for in the sub-array to the right of the middle item. This process continues on the sub-array as well until the size of the subarray reduces to zero.
Example
public class BinarySearch { public static void main(String args[]){ int array[] = {10, 20, 25, 57, 63, 96}; int size = array.length; int low = 0; int high = size-1; int value = 25; int mid = 0; mid = low +(high-low)/2; while(low<=high){ if(array[mid] == value){ System.out.println(mid); break; } else if(array[mid]<value) low = mid+1; else high = mid - 1; } mid = (low+high)/2; } }
Output
2
- Related Articles
- Java Program to implement Binary Search on char array
- Java Program to implement Binary Search on long array
- Java Program to implement Binary Search on double array
- Java Program to implement Binary Search on float array
- Java Program to implement Binary Search on an array
- Swift Program to Implement Binary Search Algorithm
- C++ Program to Implement Randomized Binary Search Tree
- Python Program to Implement Binary Search without Recursion
- Python Program to Implement Binary Search with Recursion
- Java program to implement linear search
- C++ Program to Implement self Balancing Binary Search Tree
- C++ Program to Implement a Binary Search Algorithm for a Specific Search Sequence
- Java Program to search ArrayList Element using Binary Search
- C++ Program to Implement a Binary Search Tree using Linked Lists
- Java Program for Binary Search (Recursive)

Advertisements