100 likes | 229 Views
HKOI 2005 Intermediate Training. Searching and Sorting 9/4/2005. 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. Linear Search. Or called Sequential Search
E N D
HKOI 2005Intermediate Training Searching and Sorting 9/4/2005
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
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
Binary Search • Requirement: the list of data is sorted • The idea is based on the elimination of impossible region
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
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 ); }
Binary Search • Complexity: O(log N)
Interpolation Search • Requirement: the list of data is sorted
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 begin 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) ***} end;