Discussion Forums

New User? Please read instructions!

What is binary search? write a C program for binary search  

  RSS

thiyagarajan
Eminent Member
Joined: 1 month  ago
Posts: 26
27/01/2017 9:49 am  

What is binary search? write a C program for binary search


ReplyQuote
prakash
Eminent Member
Joined: 1 month  ago
Posts: 20
16/02/2017 2:47 pm  

C program for binary search:

 

#include <stdio.h>

int main()

{

     int c, n, first, last, mid, search, a[250];

     printf("Please enter number of elements\n");

     scanf("%d",&n);

 

     printf("Enter the elements one by one\n", n);

 

     for ( c = 0 ; c < n ; c++ )

     {

          scanf("%d",&a[c]);

     }

 

     printf("Enter the element to be searched\n");

     scanf("%d",&search);

 

     first = 0;

     last = n - 1;

     mid = (first+last)/2;

 

     while( first <= last )

     {

           if ( a[mid] < search )

          {

               first = mid + 1;    

          }

          else if ( a[mid] == search ) 

         {

               printf("%d is found at the location %d.\n", search, mid+1);

               break;

         }

         else

         {

              last = mid - 1;

         }

 

         mid = (first + last)/2;

     }

     if ( first > last )

         printf("Element %d is not found in the list\n", search);

 

     return 0;   

}

 

Output:

Please enter number of elements

3

Enter the elements one by one

5

3

8

Enter the element to be searched

3

3 is found at the location 2.

 


ReplyQuote
  
Working

Please Login or Register

Ask your questions or clarify your/others doubts from,

✅ Online Discussion Forums by Fresh2Refresh.com





Share this website !!!
Facebook Twitter Linkedin

Close
We Support JALLIKATTU !!!
We Support JALLIKATTU!
By Fresh2Refresh.com
Show Your Support as well. Thanks!