ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming

C Program to perform Binary Search operation Using Arrays

Updated on February 17, 2013

Binary Search Operation in C Programming helps in finding the position of any no. in the sorted list . The requirement of this program to work upon is therefor a sorted list of array elements.

This written program works in two steps . Firstly , It sorts the entered elements in increasing order and then start the Search operation . For Searching the desired element , it always strike the middle element of the sorted list .

If the middle element is what we are looking for , then it will give us its position else it will either search the upper half or lower half portion of the sorted list depending on whether the no. we are searching for is greater or less than the middle number .

Binary Search operation reduces the number to be checked each time by a factor of 2 . Copy the Following Source code and save it with extension *.c or *.cpp .

#include<stdio.h>
#include<conio.h>
int main()
{ 
  int n, i, j, temp , a[100];
  int beg, end, mid, target;
  printf("Enter the total integers you want to enter (make it less than 100):\n");
  scanf("%d",&n);
  printf("Enter the %d integer array elements:\n",n);
    for(i=0;i<n;i++)
  {
    scanf("%d",&a[i]);
  }
    for(i=0;i<n-1;i++)
  {  
    for(j=0;j<n-i-1;j++)
    {
      if(a[j+1]<a[j])
      {
        temp = a[j];
        a[j] = a[j+1];
        a[j+1] = temp;
      }
    }
  }
  printf("The sorted numbers are:");
  for(i=0;i<n;i++)
  {
    printf("%2d",a[i]);
  }
    beg=0;
    end=n-1;  
  printf("\nEnter the number to be searched:\n");
  scanf("%d",&target);
   do
  {
    mid=(beg+end)/2;
    if(target<a[mid])
              {
      end=mid-1;     
      }
    else
     {  beg=mid+1;  }
  }
  while((beg<=end)&&a[mid]!=target);
  if(a[mid]==target)
  {
    printf("\n %d found at location %d",target,mid+1);
  }
  else
  {
    printf("\n %d not found!",target);
  }
  getch();
}

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.