Wednesday, 21 September 2011

Binary Search in Single dimension array

This is for my juniors who are finding it difficult to code in labs because of horrible lab teachers+theory teachers :P I hope my juniors wont suffer like me!

 To write a C program to input N real integers in ascending order into single dimension array and to conduct a Binary Search for a given integer.

Here's how this algorithm works :




#include<stdio.h>
main(0
{
   int i,n,a[100],begin,end,mid,flag=-1,k;//Comparing with the above  pic, here min=begin,max=end
   printf("Enter the size of the array\n");
   scanf("%d",&n);
   printf("Enter the array in the increasing order\n");
   for(i=0;i<n;i++)
    scanf("%d",&a[i]);
  printf("Enter the key number to be searched\n");
  scanf("%d",&k);
  begin=0;
  end=n-1;
  while(begin<=end)
  {
    mid=(begin+end)/2;
    if(k==a[mid])
    {
      flag=mid;
      break;
     }
   else if(k>a[mid])
     begin=mid+1;
   else
     end=mid-1;
  }
if(flag==-1)
 printf("FAILURE.Element not found in the array\n");
else
 printf("SUCCESS.The element is found in the array at location %d",flag);
}

Remember to enter the elements in ascending order! :)

No comments:

Post a Comment