11.07.2015 Views

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Sec. 9.1 Searching Unsorted <strong>and</strong> Sorted Arrays 303n−1∑T(n) = np n + (i + 1)p i .Wh<strong>at</strong> happens to the equ<strong>at</strong>ion if we assume all the p i ’s are equal (except p 0 )?i=0n−1∑T(n) = p n n + (i + 1)p= p n n + pi=0n∑ii=1n(n + 1)= p n n + p2= p n n + 1 − p nnn(n + 1)2= n + 1 + p n(n − 1)2Depending on the value of p n , n+12≤ T(n) ≤ n.For large collections of records th<strong>at</strong> are searched repe<strong>at</strong>edly, sequential searchis unacceptably slow. One way to reduce search time is to preprocess the recordsby sorting them. Given a sorted array, an obvious improvement over simple linearsearch is to test if the current element in L is gre<strong>at</strong>er than K. If it is, then we knowth<strong>at</strong> K cannot appear l<strong>at</strong>er in the array, <strong>and</strong> we can quit the search early. But thisstill does not improve the worst-case cost of the algorithm.We can also observe th<strong>at</strong> if we look first <strong>at</strong> position 1 in sorted array L <strong>and</strong> findth<strong>at</strong> K is bigger, then we rule out position 0 as well as position 1. Because moreis often better, wh<strong>at</strong> if we look <strong>at</strong> position 2 in L <strong>and</strong> find th<strong>at</strong> K is bigger yet?This rules out positions 0, 1, <strong>and</strong> 2 with one comparison. Wh<strong>at</strong> if we carry this tothe extreme <strong>and</strong> look first <strong>at</strong> the last position in L <strong>and</strong> find th<strong>at</strong> K is bigger? Thenwe know in one comparison th<strong>at</strong> K is not in L. This is very useful to know, butwh<strong>at</strong> is wrong with the conclusion th<strong>at</strong> we should always start by looking <strong>at</strong> the lastposition? The problem is th<strong>at</strong>, while we learn a lot sometimes (in one comparisonwe might learn th<strong>at</strong> K is not in the list), usually we learn only a little bit (th<strong>at</strong> thelast element is not K).The question then becomes: Wh<strong>at</strong> is the right amount to jump? This leads usto an algorithm known as Jump Search. For some value j, we check every j’thelement in L, th<strong>at</strong> is, we check elements L[j], L[2j], <strong>and</strong> so on. So long as K isgre<strong>at</strong>er than the values we are checking, we continue on. But when we reach a

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!