Example of Arrays.binarySearch in Java
November 12, 2023
Arrays.binarySearch
searches the element in the given array by binary search algorithm. As an input Arrays.binarySearch
takes the sorted
array and the key. Start and last index argument is optional.
Find the sample example.
BinarySearchDemo.java
package com.util; import java.util.Arrays; import java.util.List; public class BinarySearchDemo { public static void main(String[] args) { //with integer data int[] intArr={1,2,3,4,5}; int index= Arrays.binarySearch(intArr, 0, 4,3); System.out.println(index); //with String data String[] strArr = {"ABC","EFG","HIJ","KLM"}; index = Arrays.binarySearch(strArr,"HIJ"); System.out.println(index); } }
2 2