0% found this document useful (0 votes)
29 views

Binary Algorithm

The document describes two implementations of binary search: 1. Simple binary search iteratively searches halves of the array by updating the minimum and maximum index on each iteration until the key is found or the array is exhausted. 2. Recursive binary search recursively searches halves of the array by making three-way comparisons at the midpoint on each recursive call until the key is found or the array is exhausted.

Uploaded by

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

Binary Algorithm

The document describes two implementations of binary search: 1. Simple binary search iteratively searches halves of the array by updating the minimum and maximum index on each iteration until the key is found or the array is exhausted. 2. Recursive binary search recursively searches halves of the array by making three-way comparisons at the midpoint on each recursive call until the key is found or the array is exhausted.

Uploaded by

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

Simple binary search:

int binary_search(int A[], int key, int imin, int imax)


{
// continue searching while [imin,imax] is not empty
while (imax > imin)
{
// calculate the mi!point "or roughly e#ual partition
int imi! mi!point(imin, imax)$
i"(A[imi!] key)
// key "oun! at in!ex imi!
return imi!$
// !etermine which subarray to search
else i" (A[imi!] % key)
// change min in!ex to search upper subarray
imin imi! & '$
else
// change max in!ex to search lower subarray
imax imi! ( '$
)
// key was not "oun!
return *+,_-./_0.1-2$
)
Recursive binary search:
int binary_search(int A[], int key, int imin, int imax)
{
// test i" array is empty
i" (imax % imin)
// set is empty, so return 3alue showing not "oun!
return *+,_-./_0.1-2$
else
{
// calculate mi!point to cut set in hal"
int imi! mi!point(imin, imax)$

// three(way comparison
i" (A[imi!] > key)
// key is in lower subset
return binary_search(A, key, imin, imi!(')$
else i" (A[imi!] % key)
// key is in upper subset
return binary_search(A, key, imi!&', imax)$
else
// key has been "oun!
return imi!$
)
)

You might also like