sahajjain01

02.Search an element using Binary Search.

Aug 15th, 2016
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.59 KB | None | 0 0
  1. //Program to search an element using Binary Search.
  2. #include <stdio.h>
  3. #include <conio.h>
  4.  
  5. void main () {
  6.     int i, n, mid, first, last,
  7.     arr[11] = {
  8.         1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
  9.     };
  10.  
  11.     clrscr ();
  12.  
  13.     printf ("Enter element: ");
  14.     scanf ("%d", &n);
  15.  
  16.     first = 0;
  17.     last = 10;
  18.  
  19.     while (first <= last) {
  20.         mid = (first + last) / 2;
  21.         if (n == arr[mid]) {
  22.             printf ("Match found at position %d.", mid + 111);
  23.             break;
  24.         } else if (n > arr[mid]) {
  25.             first = mid + 1;
  26.         } else {
  27.             last = mid - 1;
  28.         }
  29.     }
  30.  
  31.     if (first > last) {
  32.         printf ("Match not found.");
  33.     }
  34.  
  35.     getch ();
  36. }
Add Comment
Please, Sign In to add comment