- 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
Search elements in a sorted object array in Java
An element can be searched in a sorted object array in Java by using the method
java.util.Arrays.binarySearch(). This method returns the index of the required element if it is available in the array, otherwise it returns (-(insertion point) - 1) where the insertion point is the position at which the element would be inserted into the array. A program that searches the required element in a sorted object array is given as follows −
Example
import java.util.Arrays; public class Demo { public static void main(String[] args) { String str[] = { "P", "M", "A", "T", "D"}; Arrays.sort(str); System.out.println("The sorted array of strings is: "); for (String i : str) { System.out.println(i); } int pos = Arrays.binarySearch(str, "M"); System.out.println("The element M is at index: " + pos); } }
Output
The sorted array of strings is: A D M P T The element M is at index: 2
Now let us understand the above program.
The elements of str are sorted using Arrays.sort() method. Then the sorted string array is printed using for loop. A code snippet which demonstrates this is as follows −
String str[] = { "P", "M", "A", "T", "D"}; Arrays.sort(str); System.out.println("The sorted array of strings is: "); for (String i : str) { System.out.println(i); }
The method Arrays.binarySearch() is used to find the index of element “M”. Then this is displayed. A code snippet which demonstrates this is as follows −
int pos = Arrays.binarySearch(str, "M"); System.out.println("The element M is at index: " + pos);