JXNVCE ALGO-LOG YouJin Jung

RANDOMIZED-BINARY-SEARCH-ALGORITHM

#include <iostream>
#include <ctime>
using namespace std;

int getRandom(int x, int y) {
    srand(time(NULL));
    return (x + rand()%(y-x+1));
}

int randomizedBinarySearch(int arr[], int l, int r, int x) {
    while (l <= r) {
        int m = getRandom(l, r);
        if (arr[m] == x)  return m;

        if (arr[m] < x) l = m + 1;

        else r = m - 1;
    }
    return -1;
}
 
int main(void) {
    int arr[] = {2, 3, 4, 10, 40};
    int n = sizeof(arr)/ sizeof(arr[0]);
    int x = 10;
    int result = randomizedBinarySearch(arr, 0, n-1, x);
    (result == -1)? printf("Element is not present in array") : printf("Element is present at index %d", result);
    return 0;
}