Saturday, October 30, 2021

Binary search Programs

Binary Search Programs

Binary search Programs

Binary search is used to search an element in a sorted array. It is an efficient search algorithm in a sorted array. If the array is not sorted then the binary search is not working correctly. So when we use binary search algorithm; we have to make sure that the array is sorted.

Pascal, Python and Java Programs are given below for Binary Search:

Pascal Program for Binary Search

 
program binsearch;

{Function for binary Search
first parameter - integer number which we search in the sorted array
second parameter - is the sorted array in which we search the number}

function BinarySearch(X: Integer; A: Array of Integer): boolean;
var
  L, R, M, Cur: Integer;
  answer :boolean;
begin
  answer := false;
  if Length(A) = 0 then Exit;
  L := Low(A);
  R := High(A);
  while ((L <= R) AND (answer = false)) do
  begin
    M := ((L+R) div 2);
    Cur := A[M];
    if (X = Cur) then begin
	answer := true;
    end;
    if (X > Cur) then
       L := M +1
    else
      R := M-1;

  end;
  BinarySearch := answer;
end;

{Main Program}
var
  n: array [0..9] of integer;
  inp: boolean;
  num:integer;

begin
  n[0]:=12;
  n[1]:=15;
  n[2]:=20;
  n[3]:=27;
  n[4]:=29;
  n[5]:=30;
  n[6]:=78;
  n[7]:=81;
  n[8]:=89;
  n[9]:=95;
  write('Enter a number to search?');
  readln(num);
  inp:=BinarySearch(num,n);
  writeln(inp);
  readln;
end.

Python Program for Binary Search

 
def BinarySearch(X, A):     
    if not A:
        print('Array Empty')
    else:
        answer=False
        L=0
        R=len(A)-1
        while ((L<=R) and (answer==False)):
            M=((L+R) // 2)
            Cur=A[M]
            if (X==Cur):
                answer=True
            if (X>Cur):
                L=M+1
            else:
                R=M-1
    return answer

n=[10,12,45,60,70,80,90]
num=int(input('Enter a number to Search?'))
inp=BinarySearch(num, n)
print('Search number ', num, ' is ' , inp)

Java Program for Binary Search

import java.util.Scanner;

public class BinarySearch
{

	public boolean Search(int X, int[] A)
	{
		int L,R,M, Cur;
		boolean answer;
		answer=false;	
		if (A.length== 0)  
		{
			return answer;
		}
		else
		{
			L=0;
  			R=A.length-1;
			while ((L <= R) && (answer == false)) 
			{
 				M =(int) Math.floor((L+R) / 2);
				Cur= A[M];
				if (X == Cur)
				{
					answer = true;
				}
    				if (X > Cur)
					L = M +1;
    				else
      					R = M-1;  				
			}
			return answer;
		}
	}

	//Main Program
	public static void main(String arg[])
	{
		int[] arr={10,30,45,67,80,90,100};
		boolean f;
		int num;
		Scanner sc = new Scanner(System.in);
		System.out.print("Enter a number to search in the array");
		num=sc.nextInt();
		BinarySearch bs=new BinarySearch();
		f=bs.Search(num,arr);
		System.out.println(f);

	}

}



No comments:

Post a Comment