Binary search in C++

Binary search is used to quickly find a value in a sorted sequence of numbers

Source code :

#include<iostream>

using namespace std;

int main(){
    
    
    int search_array[] = {0,1,4,5,7,9,13,17,19,25,85,456,594};
    
    int key = 17; //Element to search
    
    int i, size = sizeof(search_array)/sizeof(search_array[0]);
    int found = 0, position, first, last ,middle;
    
    
    first = 0;
    last = size - 1;
    middle = (first+last)/2;
 
    while (first <= last){
        if (search_array[middle] < key){
            first = middle + 1;
        }else if (search_array[middle] == key){
            found = 1;
            position = middle;
            break;
        }else{
            last = middle - 1;
        }
      middle = (first + last)/2;
   }

    
    if(found){
        cout<<"Element "<<key<<" found at position "<<position;
    }else{
        cout<<"Element not found";
    }
    

    return 0;

}

Output :

Element 17 found at position 7

Output :


                

Comments :