Sunday, May 3, 2015

Binary Search

// Binary_Search.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream"
using namespace std;
template <class T>
int binarySearch(T a[], int n, T&x)
{
       int left = 0; //left end of segment
       int right = n - 1; //Right end of segment
       while (left <= right)
       {
             int middle = (left + right) / 2; //Middle of segment
             if (x == a[middle])
                    return middle;
             if (x > a[middle])
                    left = middle + 1;
             else
                    right = middle - 1;
       }
       return -1; // x not found
}

int _tmain(int argc, _TCHAR* argv[])
{
       int a[10], n, t;
       cout << "Enter the size:" << "\n";
       cin >> n;
       cout << "Enter the elements in sorted order:" << "\n";
       for (int i = 0; i <= n; i++)
             cin >> a[i];
       cout << "Enter the element to search: ";
       cin >> t;
       int f = binarySearch(a, n, t);
       if (f == -1)
             cout << "Element not found: " << "\n";
       else
             cout << "Element forund at index:" << "\n";
       system("pause");
       return 0;
}