+92 332 4229 857 99ProjectIdeas@Gmail.com

Binary Search (C++)


Binary Search
binarySearch() function has 3 input parameters:
first is the starting address of the array.
second is the size of the array.
third is the value to be searched.
It returns 1 if the value is found and returns 0 in case if value is not found.

Code

#include "stdafx.h"
#include "iostream"
#include "conio.h"

using namespace std;

bool binarySearch(int* arr, int arraySize, int keyToFind)
{
    int left = 0;
       int right = arraySize - 1;
       int mid = 0 ;

     while (left <= right)
     {
         mid = (left + right) / 2;

         if (keyToFind == arr[mid])
         {
              return true;
         }
         else if (keyToFind > arr[mid])
              left = mid + 1;
         else
              right = mid - 1;
     }
return false;
}

int main()
{
    int arraySize = 0;
    int keyToFind = 0;
    int*arr;

    cout<<"ENTER THE SIZE OF THE ARRAY > ";
    cin>>arraySize;

    arr=new int[arraySize];

    cout<<"ENTER VALUES INTO THE ARRAY : "<<endl;
    for (int i=0; i<arraySize; i++)
    {
              cout<<"arr["<<i<<"] > ";
        cin>>arr[i];  
    }

    cout<<"ENTER THE VALUE TO SEARCH > ";
    cin>>keyToFind;

    cout<<binarySearch( arr, arraySize, keyToFind );cout<<endl;

       _getche();
       return 0;
}

0 comments: