Skip to main content

Binary search in C.

01  #include<stdio.h>
02  int main()
03   {
04    int c, first, last, middle, n, search, array[100]; 
05    printf("Enter number of elements\n");
06    scanf("%d",&n); 
07    printf("Enter %d integers\n", n); 
08    
09    for ( c = 0 ; c < n ; c++ ) 
10    scanf("%d",&array[c]); 
11    printf("Enter value to find\n");
12    scanf("%d",&search); 
13     first = 0; 
14     last = n - 1; 
15     middle = (first+last)/2; 
16     
17  while( first <= last ) 
18     {
19       if ( array[middle] < search ) 
20         first = middle + 1;    
21       else if ( array[middle] == search ) 
22         {
23          printf("%d found at location %d.", search, middle+1); 
24          break; 
25         }
26       else
27          last = middle - 1; 
28          middle = (first + last)/2; 
29     }
30    if ( first > last ) 
31    printf("Not found! %d is not present in the list.\n", search); 
32    
33    return 0;   
34   }

 
 OUTPUT :
 
 (1st Run)
 
 Enter the number of elements
 5
 
 Enter 5 integers
 12
 13
 14
 15
 16
 
 Enter the value to find
 14
 
 14 is found at location 3.
 
 (2nd Run)
 
 Enter the number of elements
 5
 
 Enter 5 integers
 12
 13
 14
 15
 16
 
 Enter the value to find
 23
 
 Not found! 23 is not present in the list.


Popular posts from this blog

What is public static void main(String args[]) ?