Simple binary search

PHOTO EMBED

Sun Jan 16 2022 06:59:21 GMT+0000 (Coordinated Universal Time)

Saved by @vaibhav_55 #binarysearch

//whenever there is sorted array first think of binary search

int binarySearch(vector<int> &ar, int target)
{

    int low = 0, high = ar.size() - 1;

    while (low <= high)
    {
        int mid = low + (high - low) / 2;

        if (ar[mid] == target)
            return mid;
        else if (ar[mid] > target)
            high = mid - 1; // go to left
        else
            low = mid + 1; // go to right
    }

    return -1; // if element is not found
}

//the above solution is only ,if array is sorted in ascending order
//for descending sorted array condition's to go to left and right reverse

//time complexity :- O(logn);
content_copyCOPY