12.07.2015 Views

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

SHOW MORE
SHOW LESS
  • No tags were found...

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 319Let p i be the probability that K is in position i of L. When K is not in L,sequential search will require n comparisons. Let p 0 be the probability that K isnot in L. Then the average cost T(n) will beT(n) = np 0 +n∑ip i .What happens <strong>to</strong> the equation if we assume all the p i ’s are equal (except p 0 )?i=1T(n) = p 0 n += p 0 n + pn∑ipi=1n∑ii=1n(n + 1)= p 0 n + p2= p 0 n + 1 − p 0nn(n + 1)2= n + 1 + p 0(n − 1)2Depending on the value of p 0 , n+12≤ T(n) ≤ n.For large collections of records that are searched repeatedly, sequential searchis unacceptably slow. One way <strong>to</strong> reduce search time is <strong>to</strong> preprocess the recordsby sorting them. Given a sorted array, an obvious improvement over simple linearsearch is <strong>to</strong> test if the current element in L is greater than K. If it is, then we knowthat K cannot appear later 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 that if we look first at position 1 in sorted array L <strong>and</strong> findthat K is bigger, then we rule out positions 0 as well as position 1. Because more isoften better, what if we look at position 2 in L <strong>and</strong> find that K is bigger yet? Thisrules out positions 0, 1, <strong>and</strong> 2 with one comparison. What if we carry this <strong>to</strong> theextreme <strong>and</strong> look first at the last position in L <strong>and</strong> find that K is bigger? Then weknow in one comparison that K is not in L. This is very useful <strong>to</strong> know, but what iswrong with this approach? While we learn a lot sometimes (in one comparison wemight learn that K is not in the list), usually we learn only a little bit (that the lastelement is not K).The question then becomes: What is the right amount <strong>to</strong> jump? This leads us<strong>to</strong> an algorithm known as Jump Search. For some value j, we check every j’th

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

Saved successfully!

Ooh no, something went wrong!