This preview shows pages 1–3. Sign up to view the full content.
Binary Search and Binary Search Trees
Binary Search
•
Problem:
o
Find element X in array A[] (x ε A[]) ?
•
Requirements:
o
Array A[] has to be sorted.
o
Searching algorithm to find X in A[]
Is X greater than or less
than A[N/2]? (X <> A[N/2])
If it is equal, then we are done.
int search(A,N,X){
if(x == A[N/2]) {
//Found the element we were looking for
return n/2;
}
if(x > A[N/2]){
//Continue searching below current element
search (A[1…n/21], n/2, x);
}
else{
//Continue searching above current element
search(A[1.
..n/2+1], n/2,x);
}
}
If you have an algorithm like this, you'll have O(log N) which is much
better
than linear. It saves you (1/2)n amount of work.
T(N) = log
2
(n)
Example:
This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentT(64) = 1 + T(32) = 6
T(32) = 1 + T(16) = 5
T(16) = 1 + T(8) = 4
T(8) = 1 + T(4) = 3
T(4) = 1 + T(2) = 2
T(2) = 1 + T(1) = 1
If the number you are looking for is equal to 2^32, it will take roughly
32 comparisons to find it.
Insertion And Deletion
This is the end of the preview. Sign up
to
access the rest of the document.
 Fall '08
 Staff
 Binary Search, Data Structures, Sort

Click to edit the document details