Binary search in C

Source code :

#include<stdio.h>



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){
        printf("Element %d found at position %d",key,position);
    }else{
        printf("Element not found");
    }
    

    return 0;

}

Output :

Element 17 found at position 7

Output :


                

Comments :