C++ Program to Implement Binary Search

C++ Program to Implement Binary Search

// CPP Program to Implement Binary Search

#include <iostream>

using namespace std;

int BinarySearch(int A[], int low, int high, int key)
{
   while(low <= high)
   {
   	 int mid = (low + high) / 2;

   	 if(A[mid] == key)
   	 {
   	 	return mid;
	 }
	 else if(A[mid] > key)
	 {
	 	high = mid - 1;
	 }
	 else
	 {
	 	low = mid + 1;
	 }
   }
    return -1;
}

int main()
{
    int A[] = { 2, 3, 4, 10, 40 };

    int n = sizeof(A) / sizeof(A[0]);
    int key, i;

    cout << "\nArray Elements :--> ";
	for (i = 0; i < n; i++)
		cout << A[i] << " ";

    cout << "\nEnter Element to Search :--> ";
    cin >> key;

    int result = BinarySearch(A, 0, n - 1, key);

    if(result == -1)
    {
		 cout << "\nElement is not present in array";
	}
	else
	{
		cout << "\nElement is present at index " << result;
	}

    return 0;
}

Output:

Run 1:
Array Elements :--> 2 3 4 10 40
Enter Element to Search :--> 4

Element is present at index 2


Run 2:
Array Elements :--> 2 3 4 10 40
Enter Element to Search :--> 11

Element is not present in array