Download presentation
Presentation is loading. Please wait.
1
HKOI 2005 Intermediate Training
Searching and Sorting 9/4/2005
2
Introduction Task of searching for a key in a list or in an array
Searching algorithms will be discussed: Linear Search Binary Search Interpolation Search
3
Linear Search Or called Sequential Search
checking every element of a list sequentially until a match is found Complexity: O(N) On average, N/2 comparisons is needed Best case: the first element searched is the value we want Worst case: the last element searched is the value we want
4
Binary Search Requirement: the list of data is sorted
The idea is based on the elimination of impossible region
5
Binary Search Algorithm:
Let the current region is from A[low] to A[high] Compare key with A[midpoint] If key<A[midpoint], then A[midpoint] to A[high] does not contain the key If key>A[midpoint], then A[low] to A[midpoint] does not contain the key Repeat the above process until the key is found
6
Binary Search int search( key, r ) typekey key; dataarray r;
{ int high, i, low; for ( low=(-1), high=n; high-low > 1; ) { i = (high+low) / 2; if ( key <= r[i].k ) high = i; else low = i; } if ( key==r[high].k ) return( high ); else return( -1 );
7
Binary Search Complexity: O(log N)
8
Interpolation Search Requirement: the list of data is sorted
10
Interpolation Search function search( key : typekey; var r : dataarray ) : integer; var high, j, low : integer; begin low := 1; high := n; while (r[high].k >= key) and (key > r[low].k) do j := trunc( (key-r[low].k) / (r[high].k-r[low].k) * (high-low) ) + low; if key > r[j].k then low := j+1 else if key < r[j].k then high := j-1 else low := j end; if r[low].k = key then search := low {*** found(r[low]) ***} else search := -1; {*** notfound(key) ***}
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.