set4_sol

set4_sol - CS112 Spring 2011: Problem Set 4...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
CS112 Spring 2011: Problem Set 4 Linear/Sequential Search ------------------------------------------------------------------------ 1. Exercise E3.11*, page 118 of the textbook. Two people compare their favorite playlists for matching songs. The first playlist has /n/ songs, and the second has /m/. Each is stored in an array, in no particular order. Describe an algorithm to find the common songs in these lists (intersection). 1. What is the worst-case big /O/ running time of your algorithm? Make sure to state the basic operations used in your analysis of running time. 2. What is the best-case big /O/ running time of your algorithm? Explain clearly, including all book-keeping needed to achieve this best case. *SOLUTION* Algorithm: For each song in the first playlist, do a linear search in the second and if a match is found, add it to the output list. Basic operation is a comparison between a pair of songs. 1. In the worst case, there are no common songs. Eevery song in the first list gets compared with every song in the second, for a total of /n*m/ comparisons, and therefore, O(/n*m/) 2. In the best case, there is a maximum number of common songs, which would be min(/m/,/n/) (number of common songs cannot exceed the length of the smaller list). Also, the least number of matches is made to find a match. Again, doing a linear search for each song in the /n/ list against the songs in the /m/ list, the first song in the /n/ list matches the first song in the /m/ list (1 comparson), the second song in the /n/ list matches the second song in the /m/ list (2 comparisons), and so on. This gives a total of: 1+2+3+. ..+min(m,n) comparisons, which is O(min(/m/,/n/)^2 ) ------------------------------------------------------------------------ 2. * Here's code for a method that implements a "lazy" sequential
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 4

set4_sol - CS112 Spring 2011: Problem Set 4...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online