How to find the index of an element in an int array?

前端 未结 19 1384
南方客
南方客 2020-11-27 02:56

How can I find an index of a certain value in a Java array of type int?

I tried using Arrays.binarySearch on my unsorted array, it only som

19条回答
  •  日久生厌
    2020-11-27 03:14

    Binary search: Binary search can also be used to find the index of the array element in an array. But the binary search can only be used if the array is sorted. Java provides us with an inbuilt function which can be found in the Arrays library of Java which will rreturn the index if the element is present, else it returns -1. The complexity will be O(log n). Below is the implementation of Binary search.

    public static int findIndex(int arr[], int t) { 
       int index = Arrays.binarySearch(arr, t); 
       return (index < 0) ? -1 : index; 
    } 
    

提交回复
热议问题