Monday, June 7, 2010

Binary Search



  1. int main() 
  2. {
  3.   int a[20] = {0};
  4.   int n,

  5. i, j, temp;   int *beg,

  6. *end, *mid, target;
      printf(" enter the total integers you want to enter (make it less then 20):\n");
  7.   scanf("%d", &n);
  8.   if (n >= 20) return 0;   //  ouch!
  9.   printf(" enter the integer array elements:\n" );
  10.   for(i = 0; i < n; i++)
  11.   {
  12.     scanf("%d", &a[i]);
  13.   }
  14. // sort the loaded array, a  must for binary search!
  15.   // you can apply qsort or  other algorithms here
  16.   for(i = 0;  i < n-1; i++)
  17.   { 
  18.     for(j = 0; j < n-i-1; j++)
  19.     {
  20.       if (a[j+1] < a[j])
  21.       {
  22.         temp = a[j];
  23.         a[j] = a[j+1];
  24.         a[j+1] = temp;
  25.       }
  26.  }
  27.  }
  28. printf(" the sorted numbers  are:");
  29.  for(i = 0; i < n; i++)
  30.   {
  31.  printf("%d ", a[i]);


  32.   }
      // point to beginning and end of the array

  33.   beg = &a[0];
      end = &a[n];  // use n = one element past the loaded array!
  34.   printf("\n beg points to address %d and end to %d",beg, end);  // test
  35.   // mid should point somewhere in the middle of these addresses
  36.   mid = beg += n/2;
  37.   printf("\n mid points to address %d", mid);  // test
  38.   printf("\n enter the number to be searched:");
  39.   scanf("%d",&target);
  40.   // binary search, there is an AND in the middle of while()!!!


  41.   while((beg <= end) && (*mid != target))
      {
  42.     // is the target in lower or upper half?
  43.   if (target < *mid)
  44.   {
  45.       end = mid - 1;     // new end
  46.   n = n/2;
  47.  mid = beg += n/2;  // new middle
  48.     }
  49.     else
  50.     {
  51.  beg = mid + 1;     // new beginning
  52.   n = n/2;
  53.   mid = beg += n/2;  // new middle     
  54. }
  55.   }
  56.  // did you find the target?


  57.   if (*mid == target)
      {
  58.  printf("\n %d found!", target);
  59.   }
  60.   else
  61.   {
  62. printf("\n %d not found!", target);
  63.  }
  64.   getchar();  // trap enter
  65.  getchar();  // wait
  66.   return 0;
  67. }

No comments:

Post a Comment