1 / 10

HKOI 2005 Intermediate Training

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

jason
Download Presentation

HKOI 2005 Intermediate Training

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. HKOI 2005Intermediate 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

  9. 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;

More Related