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 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 :)