Friday, April 8, 2011

#C_CODE: Binary Search

#include <stdio.h>
 
void InsertionSort(int *ptr,int size)
{
 int i,j,index;
 for(i=1;i {
  index = ptr[i];
  for(j=i; j>0&&ptr[j-1] >index; j--)
   ptr[j] = ptr[j-1];

  ptr[j] = index;
 }
}

int BinarySearch(int *ptr,int key,int size)
{
 int low,mid,high;
 low = 0;
 high = size-1;
 while(low <= high)
 {
  mid = (low + high)/2;
  if(key < ptr[mid])
   high = mid - 1;
  else if(key > ptr[mid])
   low = mid + 1;
  else
   return mid;
 }
 return -1;
}

int main()
{
 int i;
 int a[] = {5,7,0,8,4,9,6,1,3,2};
 int res;
 
 InsertionSort(a,10);
 printf("\nInsertion sort: ");
 for(i=0;i<10;i++)
  printf("%d ",a[i]);
 
 for(i=0; i<10;i++)
 {
  res = BinarySearch(a,i,10);
  if(res != -1)
   printf("\nThe value %d is found in position: %d\n",i,res);
 }

 fflush(stdin);
 getchar();
}

REF: C Programming Language-K&R

No comments: