How to do it...

Consider an array is arr of size len elements. We want to search for a number, numb, in this array, arr. Here are the steps to search for numb in the arr array using binary search:

  1. Initialize two variables, lower and upper.
  2. Calculate the middle location of the array.
  3. If the value to search, numb, is found at location arr[mid] then display Value found and exit (that is, jump to step 8).
  4. If your search value is larger than the array's middle value, confine the search to the lower half of the array. So, set the lower limit of the array to the array's middle value.
  5. If your search value is smaller than the array's middle value, confine the search to the upper half of the array. So, set the upper limit of the array to the array's middle value.
  6. Repeat steps 3 through 5 as long as upper>=lower.
  1. The execution will proceed with this step only if the value is not found. Then display Value not found and exit.
  2. Exit.

The program for searching for an element in a sorted array using the binary search technique is as follows:

//binarysearch.c

#include <stdio.h>

#define max 20
int binary_search(int[], int, int);

int main() {
int len, found, numb, arr[max], i;
printf("Enter the length of an array: ");
scanf("%d", & len);
printf("Enter %d values in sorted order \n", len);
for (i = 0; i < len; i++)
scanf("%d", & arr[i]);
printf("Enter the value to search ");
scanf("%d", & numb);
found = binary_search(arr, numb, len);
if (found == numb)
printf("Value %d is found in the list\n", numb);
else
printf("Value %d is not found in the list \n", numb);
return 0;
}

int binary_search(int arr[], int pnumb, int plen) {
int lindex = 0, mid, uindex = plen - 1, nfound;
while (uindex >= lindex) {
mid = (uindex + lindex) / 2;
if (pnumb == arr[mid]) {
nfound = arr[mid];
break;
} else {
if (pnumb > arr[mid])
lindex = mid + 1;
else
uindex = mid - 1;
}
}
return (nfound);
}

Now, let's go behind the scenes to understand the code better.