BINARY SEARCH

BINARY SEARCH 

#include <iostream>

int BinarySearch(int arr[], int n, int x)
{
    int low = 0, high = n - 1;
    while (low <= high)
    {
        int mid = (high + low) / 2;
        if (arr[mid] == x)
        {
            return mid;
        }
        else if (arr[mid] > x)
        {
            high = mid - 1;
        }
        else
        {
            low = mid + 1;
        }
    }
    return -1;
}
int main()
{
    int arr[] = {10, 20, 30, 40, 50};
    int size = sizeof(arr) / sizeof(arr[0]);
    std::cout << "The required element is at: " << BinarySearch(arr, size, 50);
}
/*
BINARY SEARCH
-mark the first index as low index and the last index as high index
-In binary search we first find the mid point of the array
-compute [(low + high)/2]
-compare x with mid value
-we come with 3 cases
-case 1: arr[mid] == x; return simply mid value
-case 2: arr[mid] > x;repeat: high = mid - 1
-case 3: arr[mid] < x;repeat: low = mid + 1
*/

Post a Comment

0 Comments