Search code examples
javaalgorithmfindelementbinary-search

Find an element in a list/array (a big list)


I'm actually doing an easy CodinGame --> I have to find if an element exists in a list.

I've tested a first solution, it was working but it wasn't really optimized (according to the machine).

So I've tried another solution but : When I test my code for this 2nd solution, it returns the right answers but when I'm submitting my code, it tells me that my solution is completely wrong (it doesn't work if the list is empty, and also if the list is huge, ...).

Please can you help me ?


Here is my first naive solution :

public static boolean check(int[] ints, int k) {
        boolean res = false;
    
        for(int i : ints){
            if(i == k){
                res = true;
                break;
            }
        }
        return res;
    }


Here is the code of my 2nd solution that is supposed to be optimized:

static boolean exists(int [] ints, int k){
        boolean res = false;
        int first = 0;
        int last = ints.length;
        int mid = (first + last)/2;
        while(first <= last){
            if( ints[mid] < k){
                first = mid +1;
            }else if (ints[mid] == k){
                res = true; 
                break;
            }else{
                last = mid -1;
            }
         mid = (first + last)/2;
         }
         if(first > last){
            res = false;
         }
         return res;
     }

Solution

  • Finally I've found the solution to my problem !!!!!

    Here it is :


    import java.util.Arrays;
    
    class A{
        static boolean exists(int[] ints, int k){
             boolean res = false;
             int index = Arrays.binarySearch(ints, k);
             if (index<0){
                 res = false;
             }else{
                 res = true;
             }
             return res;
          }
    }