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

Binary Search

The document describes binary search algorithms for searching sorted data. It presents two recursive binary search algorithms (bsearch and bsearch2) that have logarithmic time complexity for successful and unsuccessful searches. It also compares the time complexities of the two algorithms and includes diagrams of binary search trees.

Uploaded by

TahaRazvi
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Binary Search

The document describes binary search algorithms for searching sorted data. It presents two recursive binary search algorithms (bsearch and bsearch2) that have logarithmic time complexity for successful and unsuccessful searches. It also compares the time complexities of the two algorithms and includes diagrams of binary search trees.

Uploaded by

TahaRazvi
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 8

Binary search !

Binary Search Algorithm 1


error_code bsearch(itemtype *data, itemtype &target, int size,
int &pos) {
int bottom = 0, top = size - 1;
while(bottom < top) {
int mid = (bottom + top) / 2;
if (data[mid] < target) bottom = mid + 1;
else
top = mid;
}

if (top < bottom) return not_present


else { pos = bottom;
if (data[bottom] == target) return success;
else
return not_present; }
}

Binary Search Algorithm 2


error_code bsearch2(itemtype * data, itemtype &target,
int bottom, int top, int &pos) {
if(bottom <= top) {
int mid = (bottom + top) / 2;
if (data[mid] == target)
{ pos = mid;
return success; }
else if (data[mid] < target)
return bsearch2(data, target, mid+1, top, pos);
else
return bsearch2(data, target, bottom, mid - 1, pos);
else return not_present;
}

Sequential Search Tree

Binary Search Tree For bsearch


Algorithm

Binary Search Tree For bsearch2


Algorithm

Comparison of Methods
Algorithm Successful Unsuccessful
search
search
bsearch

lg2 n + 1

lg2 n + 1

bsearch2

2 lg2 n - 3

2 lg2 n

Credits
Pictures were taken from Data Structures and Program Design in C++,
by Robert L. Kruse & Alexander J. Ryba

You might also like