98

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 sometimes gives the correct answer.

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
Jeomark
  • 981
  • 1
  • 7
  • 3
  • 16
    Binary search will never work on an unsorted array. – Chris Eberle May 30 '11 at 01:57
  • Then can you suggest me something, how should i do it. Because if i sort the array, i loose track of indexes, and i need to know which index the value came from?? – Jeomark May 30 '11 at 01:59
  • EDIT: i forgot to add, i need to find array index for double values as well. – Jeomark May 30 '11 at 02:10
  • 1
    If you don't want to sort the array, just use a simple for loop to find the value. – Jamie Curtis May 30 '11 at 02:11
  • 2
    It is generally good to read documentation of functions :) From `binarySearch`: "Searches the specified array of ... for the specified value using the binary search algorithm. **The array must be sorted** (as by the sort(long[]) method) prior to making this call. *If it is not sorted, the results are undefined.* ..." –  May 30 '11 at 02:12
  • Possible duplicate of http://stackoverflow.com/questions/3384203/finding-an-element-in-an-array-in-java – Steve Chambers Nov 25 '13 at 11:50
  • You need to have the array sorted to apply binary search. – Ruchira Randana Jan 28 '16 at 05:21

19 Answers19

148
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

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Pablo Fernandez
  • 103,170
  • 56
  • 192
  • 232
  • Thanks but would it work for type double? Sorry i forgot to mention in the question, but i need to work this for double values as well. It works fine with ints though. – Jeomark May 30 '11 at 02:09
  • Yes it would, you don't have to change anything (but the array type obviously) – Pablo Fernandez May 30 '11 at 02:32
  • 62
    Actually the code doesn't work. Check [Why is indexOf failing to find the object?](http://stackoverflow.com/questions/9981823/why-is-indexof-failing-to-find-the-object) – teloon Nov 04 '12 at 11:45
  • 15
    You need to convert array to Integer[] instead of int[]. primitive arrays are not autoboxed. – Leon Helmsley Oct 09 '13 at 08:10
  • 1
    Is this really threadsafe? When I click through the source the List.asList() creates an ArrayList that is taking the the int array directly as data container (not copying) – Langusten Gustel Oct 05 '16 at 14:24
  • This will not work if primitive int type is a type an array. In case of primitive array type, box it before using: List list = IntStream.of(array) .boxed() .collect(Collectors.toList()); Then, Arrays.asList(array).indexOf(4); will give the correct index. – Purushotham CK Jan 31 '21 at 15:01
  • another use case, what if the array has two 4? mean like this {1,2,3,4,5,4,6} , how to get the both indexs fast and clean? – Hasan Othman Oct 29 '21 at 12:56
  • why can't we use `int []` – Azhar Uddin Sheikh Mar 30 '22 at 07:05
27

Another option if you are using Guava Collections is Ints.indexOf

// Perfect storm:
final int needle = 42;
final int[] haystack = [1, 2, 3, 42];

// Spoiler alert: index == 3
final int index = Ints.indexOf(haystack, needle);

This is a great choice when space, time and code reuse are at a premium. It is also very terse.

btiernay
  • 7,873
  • 5
  • 42
  • 48
19

A look at the API and it says you have to sort the array first

So:

Arrays.sort(array);
Arrays.binarySearch(array, value);

If you don't want to sort the array:

public int find(double[] array, double value) {
    for(int i=0; i<array.length; i++) 
         if(array[i] == value)
             return i;
}
Jamie Curtis
  • 918
  • 1
  • 10
  • 24
  • 8
    +1 However it should be noted that `Arrays.sort` *mutates* the input and the original array will be modified. –  May 30 '11 at 02:08
  • thank you, the 2nd method somehow worked me after adding some logic for duplicate values with different indexes. – Jeomark May 30 '11 at 03:33
16

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

Dalvinder Singh
  • 1,073
  • 1
  • 12
  • 19
7

You can use modern Java to solve this problem. Please use the code below:

static int findIndexOf(int V, int[] arr) {
    return IntStream.range(0, arr.length)
                    .filter(i->arr[i]==V)
                    .findFirst()
                    .getAsInt();
}
Ryan M
  • 18,333
  • 31
  • 67
  • 74
Mohammad
  • 6,024
  • 3
  • 22
  • 30
  • Great! Thanks for sharing. It helps to learn about the new (optimized) built-in solutions within the language capabilities context. – Guillermo Garcia Mar 12 '20 at 08:46
  • 1
    @Simplicity's_Strength Your edit was half correct, half incorrect. Arrays do start at 0, but the [second parameter to `range` is exclusive](https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html#range-int-int-). Good catch on that first bug, though. – Ryan M Feb 06 '21 at 07:39
  • @RyanM That explains the `java.util.NoSuchElementException` i've had using this code. Well played Sir – Simplicity's_Strength Feb 08 '21 at 10:16
7
ArrayUtils.indexOf(array, value);
Ints.indexOf(array, value);
Arrays.asList(array).indexOf(value);
double-beep
  • 5,031
  • 17
  • 33
  • 41
  • 3
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – double-beep Dec 16 '19 at 17:45
3

You could convert it to a list, then use the indexOf method:

Arrays.asList(array).indexOf(1); 

http://download.oracle.com/javase/1.5.0/docs/api/java/util/Arrays.html#asList(T...) http://download.oracle.com/javase/1.5.0/docs/api/java/util/List.html#indexOf(java.lang.Object)

Victor Eronmosele
  • 7,040
  • 2
  • 10
  • 33
agmcleod
  • 13,321
  • 13
  • 57
  • 96
3

You need to sort values before using binary search. Otherwise, the manual way is to try all ints in your tab.

public int getIndexOf( int toSearch, int[] tab )
{
  for( int i=0; i< tab.length ; i ++ )
    if( tab[ i ] == toSearch)
     return i;

  return -1;
}//met

An alternative method could be to map all index for each value in a map.

tab[ index ] = value;
if( map.get( value) == null || map.get( value) > index )
    map.put( value, index );

and then map.get(value) to get the index.

Regards, Stéphane

@pst, thanks for your comments. Can you post an other alternative method ?

Snicolas
  • 37,840
  • 15
  • 114
  • 173
  • This is one way, yes. However it is *not* the only way. The use of the boolean variable `found` here is useless (and not used) and should be removed. A +1 for showing "the manual loop method" though (stylistic and formatting issues aside). –  May 30 '11 at 02:13
2

Simple:

public int getArrayIndex(int[] arr,int value) {
    for(int i=0;i<arr.length;i++)
        if(arr[i]==value) return i;
    return -1;
}
Gil SH
  • 3,789
  • 1
  • 27
  • 25
2

In case anyone is still looking for the answer-

  1. You can use ArrayUtils.indexOf() from the [Apache Commons Library][1].

  2. If you are using Java 8 you can also use the Strean API:

    public static int indexOf(int[] array, int valueToFind) {
        if (array == null) {
            return -1;
        }
        return IntStream.range(0, array.length)
                .filter(i -> valueToFind == array[i])
                .findFirst()
                .orElse(-1);
    }
    

    [1]: https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/ArrayUtils.html#indexOf(int[],%20int)

Deep Shah
  • 75
  • 6
2
    Integer[] arr = { 0, 1, 1, 2, 3, 5, 8, 13, 21 };
    List<Integer> arrlst = Arrays.asList(arr);
    System.out.println(arrlst.lastIndexOf(1));
alok
  • 2,718
  • 21
  • 17
1

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;
    }
1

I see a lot of solutions here that are not working. The most upvoted solution used an array of Integer, instead of offering a solution to an int array. It is as simple as this:

Arrays.stream(yourArray).boxed().toList().indexOf(number)
Hugo Vinhal
  • 305
  • 1
  • 15
0

You can do it like this:

 public class Test {

public static int Tab[]  = {33,44,55,66,7,88,44,11,23,45,32,12,95};
public static int search = 23;

public static void main(String[] args) {
    long stop = 0;
    long time = 0;
    long start = 0;
    start = System.nanoTime();
    int index = getIndexOf(search,Tab);
    stop = System.nanoTime();
    time = stop - start;
    System.out.println("equal to took in nano seconds ="+time);
    System.out.println("Index  of searched value is: "+index);
    System.out.println("De value of Tab with searched index is: "+Tab[index]);
    System.out.println("==========================================================");
    start = System.nanoTime();
    int Bindex = bitSearch(search,Tab);
    stop = System.nanoTime();
    time = stop - start;
    System.out.println("Binary search took nano seconds ="+time);
    System.out.println("Index  of searched value is: "+Bindex);
    System.out.println("De value of Tab with searched index is: "+Tab[Bindex]);
}



public static int getIndexOf( int toSearch, int[] tab ){
     int i = 0;
     while(!(tab[i] == toSearch) )
     {  i++; }
       return i; // or return tab[i];
   }
public static int bitSearch(int toSearch, int[] tab){
    int i = 0;
    for(;(toSearch^tab[i])!=0;i++){
    }
    return i;

}

}

Added a XOR :)

Andre
  • 172
  • 2
  • 8
  • `tab.equals(toSearch)` is comparing an array with an int. Maybe `tab[i] == toSearch` instead. – Mike Samuel Nov 25 '13 at 16:27
  • This works thanks Mike... Google for binary search, some nice articles out there and its an interesting method – Andre Nov 25 '13 at 18:32
  • @Andre if you're trying to prove a point give them a level playing field (same order, same control flow): `while (tab[i] != toSearch) i++;` VS `while ((tab[i] ^ toSearch) != 0) i++;`. – TWiStErRob Dec 06 '15 at 16:53
  • 1
    In any case the this way of timing doesn't work, for me `bitSearch` is always faster than `getIndexOf`; while if I simply swap the calls to the two methods `getIndexOf` gets faster than `bitSearch`. This clearly demonstrates that the second one is always faster for some reason of JVM internals. You should be repeating the experiment many times (probably millions), averaging the values, discarding extreme values and doing a warmup that is very similar to the test. – TWiStErRob Dec 06 '15 at 16:55
0
/**
     * Method to get the index of the given item from the list
     * @param stringArray
     * @param name
     * @return index of the item if item exists else return -1
     */
    public static int getIndexOfItemInArray(String[] stringArray, String name) {
        if (stringArray != null && stringArray.length > 0) {
            ArrayList<String> list = new ArrayList<String>(Arrays.asList(stringArray));
            int index = list.indexOf(name);
            list.clear();
            return index;
        }
        return -1;
    }
Manmohan Soni
  • 6,472
  • 2
  • 23
  • 29
  • The `clear` and the `new ArrayList` are unnecessary operations. Allocating a new `ArrayList` copies the whole array, which is pointless, because `Arrays.asList` already returns a `List` which has an `indexOf` method. Clearing the copy of the list is unnecessary, GC will take it away anyway. – TWiStErRob Nov 19 '15 at 16:42
0

In the main method using for loops: -the third for loop in my example is the answer to this question. -in my example I made an array of 20 random integers, assigned a variable the smallest number, and stopped the loop when the location of the array reached the smallest value while counting the number of loops.

import java.util.Random;
public class scratch {
    public static void main(String[] args){
        Random rnd = new Random();
        int randomIntegers[] = new int[20];
        double smallest = randomIntegers[0];
        int location = 0;

        for(int i = 0; i < randomIntegers.length; i++){             // fills array with random integers
            randomIntegers[i] = rnd.nextInt(99) + 1;
            System.out.println(" --" + i + "-- " + randomIntegers[i]);
        }

        for (int i = 0; i < randomIntegers.length; i++){            // get the location of smallest number in the array 
            if(randomIntegers[i] < smallest){
                smallest = randomIntegers[i];                 
            }
        }

        for (int i = 0; i < randomIntegers.length; i++){                
            if(randomIntegers[i] == smallest){                      //break the loop when array location value == <smallest>
                break;
            }
            location ++;
        }
        System.out.println("location: " + location + "\nsmallest: " + smallest);
    }
}

Code outputs all the numbers and their locations, and the location of the smallest number followed by the smallest number.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
madbeans
  • 99
  • 1
  • 14
0

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; 
} 
Tushar Pandey
  • 4,557
  • 4
  • 33
  • 50
-1
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;
}
Rahul9191
  • 1
  • 2
-2
Integer[] array = {1, 2, 3, 4, 5, 6};

for (int i = 0; i < array.length; i++) {
    if (array[i] == 4) {
        system.out.println(i);
        break;
    }
}
Krisztián Balla
  • 19,223
  • 13
  • 68
  • 84
vani
  • 1