0% found this document useful (0 votes)
46 views2 pages

Binary Search

The document presents algorithms for binary search using both non-recursive and recursive methods. The non-recursive algorithm iteratively searches for a key in a sorted array by adjusting the search range based on comparisons. The recursive algorithm divides the array into sublists and searches for the key by calling itself until the key is found or the sublist is empty.

Uploaded by

Sk Shetty
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views2 pages

Binary Search

The document presents algorithms for binary search using both non-recursive and recursive methods. The non-recursive algorithm iteratively searches for a key in a sorted array by adjusting the search range based on comparisons. The recursive algorithm divides the array into sublists and searches for the key by calling itself until the key is found or the sublist is empty.

Uploaded by

Sk Shetty
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

2.

4 Binary Search|
Q.4 Write recursive and non recursive algorithm for binary search
using divide and conquer method
Ans.: Algorithm (Non-recursive)
Algorithm BinSearch(A[0...n-1]KEY)
I/Problem Description: This algorithm is for searching the
//element using binary search method.
/Input: An aray A from which the KEY element is to be
//searched.
//Output: It returns the index of an array element if it is
/equal to KEY otherwise it returms -1
low-0

high-n-1
while (low<high) do

m-(low+high)/2//mid ofthe arrayis obtained


if (KEY=A/m]}then
return m
else if(KEY<A[m]}then
high- m-1 //search the left sub list
else
low -m+1 /search the right sub list

return-1 //if element is not present in the list


Design &Analysis of Algorithms 2-9 Divide and Conquer and Greedy Method

Algorithm (Recursive)

Algorithm BinSearch(A,KEY,low.high)

I/Problem Description: This algorithm is for searching the //element


using binary search method
I/Anput: A is an array of elements in which the desired
l/element is to be searched
I/KEY is the element that has to be searched
//Output: It returns the index of the array element if the KEY element
is found.

I/initially low=0; and high=n-1 where n is total number


l/ of elements in the list

m=(low+high)/2; //mid of the array is obtained


if(KEY=Am))then
retum mn;
else if(KEY<A[m}) then
BinSearch(A,KEY,low.m-1)://search the left sub list
else
BinSearch(A,KEY,m+1,high);//search the right sub list

You might also like