Sunday, 15 May 2016

Program For Binary Search By Iterative and Recursive way.

In Binary search algorithm, we are going to divide a given array into two parts and solve these parts iteratively.For this we are going to find mid element and compare it with element to be found. if it is found we are going to return position i.e(mid element). If element to be found is greater than mid then we are going to set lower bound to mid+1. If element to be found is less than mid then we are going to set upper bound to mid-1. 

Program By Iterative way:
#include<stdio.h>
void main()
{
   
    int arr[20],i,n;
    int h,l,mid,x;
    printf("Enter no. of elements");
    scanf("%d",&n);
    printf("\nEnter array Elements:");
    for(i=0;i<n;i++)
    {
        scanf("%d",&arr[i]);
    }
   
    printf("\nEnter no. to be searched:");
    scanf("%d",&x);
    l=0;
    h=n-1;
    mid=(l+h)/2;
    while(l<=h)
    {
        if(arr[mid]==x)
        {
            printf("\nElements found at %d Position\n",mid);
            break;   
        }
           
            if(x>arr[mid])   
            {
                l=mid+1;
            }
            if(x<arr[mid])
            {
                h=mid-1;
            }
       
    } 

}

Program:By Recursive Way
#include<stdio.h>
int main()
{
    int arr[20];
    int i,n;
    int h,l,mid,x;
    int result;
    printf("Enter number of elements:");
    scanf("%d",&n);
    printf("Enter array elements:");
    for(i=0;i<n;i++)
    {
        scanf("%d",&arr[i]);
    }
    l=0;
    h=n-1;
    printf("enter element to be searched:");
    scanf("%d",&x);
    result=BinarySearch(arr,l,h,x);
    printf("Element found at %d Position",result);
    return(0);

}
int BinarySearch(int arr[],int l,int h,int x)
{
    while(l<=h)
    {
        int mid=(l+h)/2;
        if(arr[mid]==x)
        {
            return(mid);
            break;
        }
        if(x>arr[mid])
        {
        return(BinarySearch(arr,mid+1,h,x));
        }
        if(x<arr[mid])
        {
            return(BinarySearch(arr,l,mid-1,x));
        }
    }
   
}
Note:
The Time Complexity By Iterative way is O(n).
The Time Complexity by Recursive way is  \Theta(Logn).

No comments:

Post a Comment