March 18, 2018

Searching in Array - Binary Search

Binary search:- The binary search technique finds the target value from sorted array. 

Suppose we want to search a target page number of the book, then we won't search it from page number start to end. Rather, we will go directly at the middle of the book, If that number matches with the target number,then searching is complete.Otherwise depending upon our target value, we will go to right half or left half of the book to repeat the same process.

Binary search technique works in the same way. 



Suppose, there are 7 elements in the array which are sorted.

Let's initialize a variable named flag with 0, that will finally represent whether searching operation is performed with success or not. 

Suppose we want to search element 75 exists in the array or not,
Then the target element will be matched with middle element i.e. x[mid] of the array.
where 
beg=0
end=n-1
mid=(beg+end)/2

Initially, 

case 1: Target element will be matched with x[mid] i.e. x[3]. If it matches, then return its position. Also update flag variable let flag=1(which will indicate searching operation is performed with success).

case 2: If target element is greater than x[mid] , then the binary search technique is applied to right half of the array i.e. at
case 3: If target element is less than x[mid] , then the binary search technique is applied to left half of the array i.e. at
Above cases are checked until the array's list from beg to end contain at least one element i.e. beg<=end.

Code:


#include<stdio.h>

void main()

{

 int x[7]={10,20,25,42,60,75,92};

 int ele,pos;

 int beg,mid,end;

 int i,n=7;

 int flag=0;

 

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

  printf("\n%d",x[i]);

 

 

 printf("\nEnter the element you want to search ");

 scanf("%d",&ele);

 

 beg=0;

 end=n-1;

 

 while(beg<=end)

 {

  mid=(beg+end)/2;

   if( ele == x[mid] )

   {

    flag=1;

    pos=mid+1;

    break;

   }

   else if(ele > x[mid] )

   {

    beg=mid+1;

   }

   else if( ele < x[mid])

   {

    end=mid-1;

   }

 }
 

 if(flag==0)

 {

  printf("Element does not exist"); 

 }

 else

 {

  printf("Element found at %d",pos);

 }
  

  getch();

}

Output:



No comments:

Post a Comment