14.02.Searching_algorithms
14.02.Searching_algorithms
Search algorithms
ece.uwaterloo.ca
dwharder@alumni.uwaterloo.ca
Outline
Linear search
return false;
}
Search algorithms
4
Binary search
if ( obj == array[b] ) {
return true;
} else if ( obj < array[b] ) {
c = b – 1;
} else {
assert( obj > array[b] );
a = b + 1;
}
}
return false;
}
Search algorithms
5
Binary search
Question:
– Which of these should you choose? Does it matter, and if so, why?
int b = a + (c - a)/2;
int b = (a + b)/2;
Binary search
Question:
– Should a binary search be called on a very small list?
• Hint: What is involved in the overhead of making a function call?
Search algorithms
7
Binary search
if ( obj == array[b] ) {
return true;
} else if ( obj < array[b] ) {
c = b – 1;
} else {
assert( obj > array[b] );
a = b + 1;
}
}
Binary search
1 3 5 8 10 14 16 19 21 24 35 41 45 47 51 63
– Suggestions?
Search algorithms
9
Binary search
We will assume that the object being searched for has properties
similar to the real number where we can do linear interpolation
Interpolation search
if ( obj == array[b] ) {
return true;
} else if ( obj < array[b] ) {
c = b – 1;
} else {
assert( obj > array[b] );
a = b + 1;
}
}
return linear_search( obj, array, a, b );
}
Search algorithms
11
Interpolation search
1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 16
Search algorithms
12
Average
Algorithm Best Case Worst Case
Case
Linear Search O(n) O(n) O(n)
Binary Search O(ln(n)) O(ln(n)) O(ln(n))
Interpolation Search Q(1) O(ln(ln(n))) O(n)
Search algorithms
13
Harder search
while ( c – a > 16 ) {
int midpoint = a + (c - a)/2; // point from binary search
int b = use_binary_search ? midpoint : a + static_cast<int>(
((c - a)*(obj – array[a])) / (array[c] – array[a])
);
if ( obj == array[b] ) {
return true;
} else if ( obj < array[b] ) {
c = b – 1; Based on introspective search which
use_binary_search = ( midpoint < b );
} else {
alternates between interpolation and
a = b + 1; binary searches
use_binary_search = ( midpoint > b );
}
}
Now, the worst case is that of binary search while the best is that of
interpolation search
Average
Algorithm Best Case Worst Case
Case
Linear search O(n) O(n) O(n)
Binary search O(ln(n)) O(ln(n)) O(ln(n))
Interpolation search Q(1) O(ln(ln(n))) O(n)
Harder search Q(1) O(ln(ln(n))) O(ln(n))
Search algorithms
15
Summary
References
Wikipedia, http://en.wikipedia.org/wiki/Search_algorithm
These slides are provided for the ECE 250 Algorithms and Data Structures course. The
material in it reflects Douglas W. Harder’s best judgment in light of the information available to
him at the time of preparation. Any reliance on these course slides by any party for any other
purpose are the responsibility of such parties. Douglas W. Harder accepts no responsibility for
damages, if any, suffered by any party as a result of decisions made or actions based on these
course slides for any other purpose than that for which it was intended.