Saturday, February 21, 2015

Implementation of Binary search

AIM:
          To write a C program to implement Binary search

ALGORITHM:
            Step 1: Start the program.
            Step 2: Read the upper limit of the array as n
Step 3: Setup for loop from i=1 until i<n increment i
Step 4: Read element to array[]
Step 5: Read element to be searched in the array as search
Step 6: Assign first=0,last=n-1
Step 7: Repeat step 8 to 9 until (first<=last)
Step 8: middle=(first+last)/2
Step 9: if(search<a[middle])
            True: n=middle=1
            False : if(search>a[middle])
                        True:first=middle+1
                        False: found the element in middle+1 position
Step 10: Stop the program.

PROGRAM
#include<stdio.h>
#include<conio.h>
 int main()
{
   int c, first, last, middle, n, search, array[100];
   printf("Enter number of elements\n");
   scanf("%d",&n);
   printf("Enter %d integers in ascending order\n", n);
   for ( c = 0 ; c < n ; c++ )
   scanf("%d",&array[c]);
   printf("Enter value to find\n");
   scanf("%d",&search);
   first = 0;
   last = n - 1;
   middle = (first+last)/2;
   while( first <= last )
   {
      if ( array[middle] < search )
         first = middle + 1;   
      else if ( array[middle] == search )
      {
         printf("%d found at location %d.\n", search, middle+1);
         break;
      }
      else
         last = middle - 1;
        middle = (first + last)/2;
   }
   if ( first > last )
   printf("Not found! %d is not present in the list.\n", search);
   getch();
   return 0;  
}



OUTPUT
Enter the number of elements 5
Enter 6 integers
1
2
3
4
5
Enter the value to find 5
5 in found in the location 5



  

RESULT: Thus a C program is written to binary search and executed successfully




No comments:

Post a Comment