Search elements in a sorted object array in Java

Java 8Object Oriented ProgrammingProgramming

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

 Live Demo

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);
raja
Published on 09-Jan-2019 10:16:07
Advertisements