C Program to Implement Binary Search



Binary Search implementation using C



  1. //binary search
  2. #include<stdio.h>
  3. main()
  4. {
  5. int i, first, last, middle, n, search, array[100];
  6. printf("enter array size: ");
  7. scanf("%d",&n);
  8. printf("enter %d integers", n);
  9. for ( i = 0 ; i < n ; i++ )
  10. scanf("%d",&array[i]);
  11. printf("enter value to find\n");
  12. scanf("%d",&search);
  13. first = 0;
  14. last = n - 1;
  15. middle = (first+last)/2;
  16. while( first <= last )
  17. {
  18. if ( array[middle] < search )
  19. first = middle + 1;
  20. else if ( array[middle] == search )
  21. {
  22. printf("%d found at position %d.\n", search, middle+1);
  23. break;
  24. }
  25. else
  26. last = middle - 1;
  27. middle = (first + last)/2;
  28. }
  29. if ( first > last )
  30. printf("Not found!");
  31. return 0;
  32. }

Output


Output!