Search Algos

mail@pastecode.io avatar
unknown
java
a month ago
1.1 kB
477
Indexable
Never
class Main {
    public static void swap(int a, int b){
        int temp = a;
        a = b;
        b = temp;
    }

    public static void swap2(int[] arr){
        int temp = arr[0];
        arr[0] = arr[1];
        arr[1] = temp;
    }

    public static int search(int[] arr, int searchValue){
        for(int i=0; i<arr.length; i++){
            if(arr[i] == searchValue){
                return i;
            }
        }

        return -1;
    }

    public static int binarySearch(int[] arr, int searchValue){
        int n = arr.length;

        int si = 0;
        int ei = n-1;

        while(si <= ei){
            int mid = (si+ei)/2;

            if(arr[mid] == searchValue){
                return mid;
            } else if(arr[mid] < searchValue){
                si = mid + 1;
            } else { // arr[mid] > searchValue
                ei = mid - 1;
            }
        }

        return -1;
    }

    public static void main(String[] args) {
        int[] arr = {10,15,17,19,21,31};

        int searchValue = 10;

        System.out.println(binarySearch(arr,searchValue));
    }
}