Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to perform binary search on an array in java?
The Arrays class of java package provides you a method named binarySearch() using this method you can perform a binary search on an array in Java.
Example
import java.util.Arrays;
public class ArrayDemo {
public static void main(String[] args) {
int intArr[] = {30,20,5,12,55};
Arrays.sort(intArr);
System.out.println("The sorted int array is:");
for (int number : intArr) {
System.out.println("Number = " + number);
}
int searchVal = 12;
int retVal = Arrays.binarySearch(intArr,searchVal);
System.out.println("The index of element 12 is : " + retVal);
}
}
Output
The sorted int array is: Number = 5 Number = 12 Number = 20 Number = 30 Number = 55 The index of element 12 is: 1
Advertisements