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

前端 未结 19 1253
南方客
南方客 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:27

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

    0 讨论(0)
提交回复
热议问题