How to implement binary search in C++

1 Answer

0 votes
#include <iostream>
 
using namespace std;
    
int binary_search(int arr[], int right, int to_find) {
   int left = 0;
   while (left <= right) { 
        int mid = left + (right - left) / 2; 
    
        if (arr[mid] == to_find) 
            return mid; 
    
        if (arr[mid] < to_find) 
            left = mid + 1; 
        else
            right = mid - 1; 
    } 
    
    return -1; 
} 
    
int main(void) 
{ 
    int arr[] = { 2, 3, 6, 7, 12, 15, 17, 19 }; 
    int to_find = 7; 
      
    int i = binary_search(arr, sizeof(arr)/sizeof(arr[0]) - 1, to_find); 
      
    (i == -1) ? cout << "not found" : cout << "Found at index: " << i; 
      
    return 0; 
} 
   
   
   
/*
run:
   
Found at index: 3
  
*/

 



answered Aug 5, 2019 by avibootz
edited Aug 5, 2019 by avibootz

Related questions

2 answers 228 views
1 answer 158 views
2 answers 202 views
1 answer 179 views
...