Binary Search

Algorithm

Input	Array of integers 
Output	Loc of searched element.
Complexity	O(logn).

Binary_search(a,n)
1.	[initialize segment variables]
 Set beg:=0,end:=n and mid:=int((beg+end)/2);
2.	Repeat steps 3 to 6 while beg<= end and a[mid]!=item
3.	If item<a[mid] then : set end := mid-1;
4.	Else Set  beg:= mid+1;
5.	Set  mid := int((beg+end)/2)
6.	[end of step2]
7.	If a[mid] = item then: Set loc := mid;
8.	Else  set loc := NULL;
9.	Return loc;
10.	Exit

Algorithm Description

Here a is an sorted array with lower bound 0 and upper bound n, and item is given item of information. The variables beg, mid and end denote respectively, the beginning, end and middle locations of a segment of elements of array a. This algorithm finds the location loc of item.

C Code


//To implement Binear Search

#include<stdio.h>
#include<conio.h>

int main()
{
    int a[50],i,num,n,k=0,mid,big,end;
    printf("Enter size of array ");
    scanf("%d",&n);
    printf("Enter %d elements in sorted order\n",n);
    for(i=1;i<=n;i++)
    {
                    scanf("%d",&a[i]);                
    }
    printf("Enter element to search ");
    scanf("%d",&num);
    big=1;
    end=n;
    mid=(big+end)/2;
    while(mid>0)
    {
       if(num==a[mid])
       break;
       else if(num>a[mid])
       big=mid+1;
       else
       end=mid-1;  
       if(big>end)
       {
       printf("Number not Found!!!!");
       break;
       }
       mid=(big+end)/2;       
    }
    if(big<=end)
	    printf("Number found at position at %d",mid);
    return 0;         
}


Java Code

import java.io.*;
class binary
{
	public static void main(String args[]) throws Exception
	{
		int element,beg,end,mid,n,i,pos;
		BufferedReader cin= new BufferedReader (new InputStreamReader(System.in));
		System.out.println("enter the no. of elements");
		n=Integer.parseInt(cin.readLine());
		int arr[]=new int[n];
		System.out.println("enter the elements in ascending order");
		for(i=0;i<n;i++)
		{
			arr[i]= Integer.parseInt(cin.readLine());
			if(i>0)
			if(arr[i]<arr[i-1])
			{
				System.out.println("numbers are not in ascending order");
				System.exit(1);
			}
		}
            System.out.println("enter the element to be searched");
		element=Integer.parseInt(cin.readLine());
 		beg=0;
		end=n-1;
		mid=beg+end/2;
		while(beg<=end && arr[mid]!=element)
		{
			if(element<arr[mid])
				end=mid-1;
			
			else
				beg=mid+1;
			mid=(beg+end)/2;
		}
		
		if(beg>end)
			System.out.println("the elment is not found");
		else	
			System.out.println("the element has been found at position "+(mid+1));
	}
}