DS – Binary Search

Binary Search:

Binary Search:

  • It is another search technique to search for an element in the array.
  • In binary search, every time we find the mid element and compare with the element to be searched.
  • If element matches, we return mid location index as element index.
  • If the element is less than the mid location element, search continues only in left part of mid location.
  • If the element is higher than the mid location element, search continues in the right side part of array from mid location.
  • This process continues until element search.
  • Note: We can apply binary search only on sorted array.
#include<stdio.h>
int main()
{
            int a[50], n, i, key, found=0, low, mid, high;
            printf(“Enter length of elements : “);
            scanf(“%d”, &n);
            printf(“Enter %d elements : \n”, n);
            for(i=0 ; i<n ; i++)
{
                        scanf(“%d”, &a[i]);
            }
            printf(“Enter element to be searched :”);
            scanf(“%d”, &key);
            low=0;
            high=n-1;
            while(low<=high){
                        mid=(low+high)/2;
                        if(key<a[mid]){
                                    high=mid-1;
                        }
                        else if(key>a[mid]){
                                    low=mid+1;
                        }
                        else if(key==a[mid]){
                                    printf(“Found @ loc : %d \n”, mid);
                                    found=1;
                                    break; 
                        }
            }
            if(!found)
                        printf(“Element not found \n”);
           
            return 0;          
};

Two way serach algorithm:

Prototype:

int TwoWayLinearSearch(arr, key, n);

Algorithms Steps:

p<-0
q<-n-1
found<-0;
while(p<q)
do
            if(a[p]!=k or a[q]!=k)
                        then p<-p+1 ; q<-q-1 ;
            else
                        then found<-1; //end while
 
if(found)
            return 1`
else
            return 0
Scroll to Top