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
You can use modern Java to solve this problem. Please use the code below:
static int findIndexOf(int V, int[] arr) {
return IntStream.range(1, arr.length).filter(i->arr[i]==V).findFirst().getAsInt();
}
The easiest way is to iterate. For example we want to find the minimum value of array and it's index:
public static Pair<Integer, Integer> getMinimumAndIndex(int[] array) {
int min = array[0];
int index = 0;
for (int i = 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
index = i;
}
return new Pair<min, index>;
This way you test all array values and if some of them is minimum you also know minimums index. It can work the same with searching some value:
public static int indexOfNumber(int[] array) {
int index = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == 77) { // here you pass some value for example 77
index = i;
}
}
return index;
}
Integer[] array = {1,2,3,4,5,6};
Arrays.asList(array).indexOf(4);
Note that this solution is threadsafe because it creates a new object of type List.
Also you don't want to invoke this in a loop or something like that since you would be creating a new object every time
Copy this method into your class
public int getArrayIndex(int[] arr,int value) {
int k=0;
for(int i=0;i<arr.length;i++){
if(arr[i]==value){
k=i;
break;
}
}
return k;
}
Call this method with pass two perameters Array and value and store its return value in a integer variable.
int indexNum = getArrayIndex(array,value);
Thank you
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;
}
static int[] getIndex(int[] data, int number) {
int[] positions = new int[data.length];
if (data.length > 0) {
int counter = 0;
for(int i =0; i < data.length; i++) {
if(data[i] == number){
positions[counter] = i;
counter++;
}
}
}
return positions;
}