COMP 3403 Algorithm Analysis Part 2 Chapters 4 5. Jim Diamond CAR 409 Jodrey School of Computer Science Acadia University

Size: px
Start display at page:

Download "COMP 3403 Algorithm Analysis Part 2 Chapters 4 5. Jim Diamond CAR 409 Jodrey School of Computer Science Acadia University"

Transcription

1 COMP 3403 Algorithm Analysis Part 2 Chapters 4 5 Jim Diamond CAR 409 Jodrey School of Computer Science Acadia University

2 Chapter 4 Decrease and Conquer

3 Chapter 4 43 Chapter 4: Decrease and Conquer Idea: (a) (b) reduce instance to one smaller instance of the same problem solve the smaller instance (c) We consider three categories of decrease and conquer: decrease by a constant (which is usually 1) e.g., insertion sort, DFS, BFS e.g., binary search, exponentiation by squaring decrease by a variable amount

4 Chapter 4 44 Example: Exponentiation Consider the problem of computing a n Brute force: iteratively do n 1 multiplications: a n = a a a a a Divide and conquer: a n = a n/2 a n/2 (n > 1) Decrease by a constant: a n = a a n 1 Decrease by a constant factor: a n = (a n/2) 2 if n is an even number > 0 ( a (n 1)/2) 2 a if n is an odd number > 1 a if n = 1 Which, if any, of these have the same efficiency? Which, if any, is(are) the most efficient?

5 Chapter 4 45 Decrease by One: Insertion Sort Algorithm Insertion Sort: InsertionSort(A[0..n-1]) for i = 1 to n - 1 v = A[i] j = i - 1 while j >= 0 and A[j] > v A[j + 1] = A[j] j = j - 1 A[j + 1] = v Decrease by one: when sorting A[0..k + 1], you make use of the fact that A[0..k] is already sorted Quick and dirty analysis: there are loops nested to a depth of 2, each of which have O(n) iterations, so you might expect an overall complexity of O(n 2 )

6 Chapter 4 46 Insertion Sort: 2 E.g., after k iterations of the outer loop, we have a situation like this: That is, the numbers to the left of are sorted, and the number in bold is the next number to be inserted in the sorted list Similar to selection sort, but: 1 in IS, 0 in SS finding the next element to insert into the sorted list: finding the location to insert the next element into IS uses O(k) comparisons, SS uses 0 moves to insert the element into the sorted list IS uses O(k) data moves, SS uses O(1)

7 Chapter 4 47 Insertion Sort: 3 Concern: IS uses more data moves (O(n 2 )) than SS (O(n)) But: the number of comparisons + data moves in the inner loop of IS is data dependent SS must examine all unsorted elements to find the minimum remaining value Thus, for IS, the average case behavior may be (and is!) better than its worst case Consider the case of random data with no duplicate elements on average, the new element will be inserted halfway down the currently-sorted list this cuts down the number of comparisons and the number of data moves by 1/2 T avg (n) n 2 /4 = Θ(n 2 ) for IS

8 Chapter 4 48 Insertion Sort: 4 An interesting case to consider is that of almost sorted data here IS really improves upon SS (and QS and MS and... ): T best (n) = n 1!! Final thought: the book comments on how, by using a sentinel, we could write while A[j] > v A[j + 1] = A[j] j = j - 1 instead of while j >= 0 and A[j] > v... j = j - 1 Question for those of you who recall their computer architecture: Is that a bogus comment? why or why not?

9 Chapter 4 49 Binary Insertion Sort Observe that IS inserts an element into a sorted array We could find the insertion location by using binary search Issue: in general, binary search is better than linear search to find an element s place in a sorted array but in the case of sorted or almost-sorted arrays binary search turns out to be worse (why?) GEQ: what are the worst, average and best-case complexities for binary insertion sort?

10 Chapter 4 50 Graphs: Review A graph G = (V, E) is a (finite) set of vertices V and a set of edges E, where E { {v 1, v 2 } v 1 V, v 2 V } (in simple graphs v 1 v 2 ) it is common to write n for the number of vertices and m for the number of edges if {v 1, v 2 } E, we say v 1 is adjacent to v 2 Normally when we say graph, we mean simple graph some people study multi-graphs which allow multiple edges between pairs of vertices e.g., here is a graph with multiple edges and loops in this class we will only be using simple graphs

11 Chapter 4 51 Graph Representation for Algorithms In order to use graphs to solve problems with computer algorithms, we must be able to represent graphs in our programs adjacency matrix adjacency list An adjacency matrix (for some n-vertex graph G) is an n n matrix A, where A i,j is 1 iff v i is adjacent to v j ; otherwise A i,j is 0 An adjacency list (for some n-vertex graph G) is an array of n lists (one for each vertex), such that v i is in v j s list iff v i is adjacent to v j Most graph algorithms favour the adjacency list approach, since the size of that representation is linear in the size of the graph: Θ( V + E ) in other words, with an adjacency matrix representation, there is no hope of having an algorithm (for non-trivial problems) guaranteed to run in O( G ) time

12 Chapter 4 52 Graph Searching: Introduction A common operation on graphs is to start searching at one vertex until either all vertices have been visited (there are other possibilities, but these are the usual ideas) The search proceeds by searching from an already-visited vertex v to some vertex w which is adjacent to v if there are multiple possible choices for w, the particular graph search may dictate which one(s) are valid choices

13 Chapter 4 53 Graph Searching: DFS and BFS Two important graph search techniques are known as breadth-first search (BFS) Both techniques can be considered as decrease by one e.g., starting from one of the n vertices in a graph, we do a search of a (sub-)graph consisting of n 1 vertices Both DFS and BFS are linear in the size of the graph representation

14 Chapter 4 54 DFS vs. BFS The two algorithms are quite similar BFS uses a queue to keep track of the vertices to be visited next Since recursion automagically implements a stack, it can be easier to write a DF search than a BF search HOMEWORK!! Review textbook algorithms instead, it does the initialization and then calls a function which can be recursive note also the problems which the textbook says these algs solve Many important graph algorithms are based on these, particularly DFS e.g., finding the bi-connected components of a graph

15 Chapter 4 55 Directed Graphs (Digraphs) A directed graph G = (V, E) is a (finite) set of vertices V and a set of edges E, where E {(v 1, v 2 ) v 1 V, v 2 V } we say (v 1, v 2 ) is an edge from v 1 to v 2 A directed cycle in a digraph is a (finite) sequence of vertices v 1, v 2,..., v k such that (v i, v i+1 ) E for 1 i < k, and (v k, v 1 ) E A digraph with no directed cycle is a directed acyclic graph (dag) Algorithms on directed graphs are sometimes more complex than on undirected graphs

16 Chapter 4 56 Dags In Real Life Dags can be used to represent situations in which there is an ordering or precedence among some items Examples: manufacturing: component A must be completed before B can be started, but components C and D can be completed in either order, or in parallel car example: the engine can be completed at the same time the body is constructed, but the engine should be installed in the car before the hood is attached the foundation must be constructed before the walls are erected the wiring and plumbing must be put in before the walls are finished, but the wiring and the plumbing can be installed in either order

17 Chapter 4 57 Topological Sorting: DFS Approach A topological sorting of a digraph (V, E) with n vertices is an ordering v i1, v i2,..., v in of the vertices such that for all (v j, v k ) E, v j appears before v k in this ordering it is also true (if less clear) that every dag has a topological sorting DFS topological sort (start at any vertex with in-degree 0):

18 Chapter 4 58 Topological Sorting: Vertex Deletion Approach A decrease by one algorithm Find a source vertex (i.e., one with in-degree 0) wash, rinse, repeat

19 Chapter 4 59 Decrease by a Constant Factor: Fake Coin Problem Problem: we have n identical-looking coins, but there is one counterfeit coin which weighs less than the real ones. Given a balance scale, how can we find the fake? Solution 1: divide the coins into two piles of size n/2 (with one coin left over if n is odd) weigh the two piles if they are the same, it must be that n is odd and the left-over is the fake The recurrence equation (for the number of weighings) is T (1) = 0 T (n) = T ( n/2 ) + 1 for n > 1 this gives T (n) = lg n (which is very fast!)

20 Chapter 4 60 Decrease by a Constant Factor: Russian Peasant Multiplication Suppose you want to compute n m brilliant observation: if n is even, n m = n/2 2m if n is odd, n m = n 1 2m + m 2 So we can multiply as follows: n m remainder Using this technique requires you to only know addition, division by 2, and multiplication by 2 720

21 Chapter 4 61 Decrease by a Variable Size: Booth s Algorithm Booth s algorithm is used to speed multiplication in hardware Base 10 example: = = = Strings of 9 s don t occur frequently in base 10 numbers E.g., suppose multiplier is instead, use 0100!100 0!00 1!00 where each! represents a subtraction instead of an addition each string of the form 01 1 is replaced by (an equal length string) of the form 10! bigger savings are available with longer words

22 Chapter 4 62 Euclid s Algorithm Euclid s algorithm is based on repeated application of the equality gcd(m, n) = gcd(n, m mod n) For example, gcd(80,44) = gcd(44,36) = gcd(36, 8) = gcd(8,4) = gcd(4,0) = 4 It can be shown that the size, measured by the second number, decreases at least by half after two consecutive iterations. Therefore T (n) O(log n) Idea of proof: assume m > n GEQ: why can I do that? Consider k 1 = m mod n: if k 1 n/2, we are done (in only 1 iteration, but that s OK) otherwise k 1 > n/2; on the next iteration, we compute n mod k 1 thus k 2 must be < n/2, as required

23 Chapter 4 63 A Quick Review(?) of QuickSort Algorithm: Quicksort(A[0..n-1]) if n > 1 rearrange A so that all values in A[0..s-1] are <= A[s] % partition 1 all values in A[s+1..n-1] are > A[s] % partition 2 Quicksort(A[0..s-1]) Quicksort(A[s+1..n-1]) Notice that there is no work to be done after the recursive calls return If we can rearrange A in O(n) time, we get T (n) = T (s) + T (n s) + O(n) n > 1 As will be seen in Chapter 5, the rearrangement step is crucial to good performance

24 Chapter 4 64 Selection Problem Find the k-th smallest element in a list of n numbers Easy for k = 1 or k = n How? Not as obvious for the median: k = n/2 Example: median =? The median is commonly used in statistics as an representative value of a set of measurements in many cases the median is a better (more robust) indicator than the mean, which is sometimes used for the same purpose e.g., the mean salary at a company may be heavily influenced by the CEO s $4,000,000 salary in this case the median is $10,000, which is more representative of what the ordinary schmo is going to earn

25 Chapter 4 65 Algorithms for the Selection Problem You could sort the data in (say) Θ(n lg n) time and use k as an index into the resulting array Can we do better? Yes: take a lesson from quicksort: choose a pivot p (for example, choose the middle element as pivot) and partition the array into three parts: numbers <= p p numbers > p Example: find median of : k = 13/2 = 7; k-th element is in the right partition: reduce k by 3 iteration 2: pivot = 12, k = 4: iteration 3: pivot = 12, k = 4: k-th = 4-th element is the pivot, so the median is 12

26 Chapter 4 66 Selection Problem: Algorithmic Efficiency Consider the (relatively lucky) case where, on every iteration, the array is partitioned as evenly as possible the master throrem tells us this is Θ(n), a very good result (GEQ: do you think the complexity of this problem is Ω(n)?) In general, we won t get a reduction by half at each iteration Sadly, the worst case behaviour is Θ(n 2 ) There is a Θ(n) worst case algorithm known I m not sure I agree with that assessment: e.g., you might need it in a real time system

27 Chapter 4 67 The Game of Nim (One Pile Version) Game: there is a pile of n chips. Two players take turns removing at least 1 and at most m chips from the pile. the winner is the player that takes the last chip Q: Who wins the game the player moving first or second, if both player make the best moves possible? A (idea): It s a good idea to analyze this and similar games backwards, i.e., starting with n = 0, n = 1, n = 2,...

28 Chapter 4 68 Analyzing One-Pile Nim Example: m = 3 (fix one variable, contemplate the other) if n is 4, the first player loses regardless of his move if n is 5, 6 or 7, the first player wins by choosing 1, 2 or 3 (respectively), putting the other player in a losing situation Generalizing this, the first player has a winning strategy if n 4, 8, 12, 16,... More generally yet, the first player has a winning strategy if n mod (m + 1) 0 specifically, the first player s winning strategy is to remove n mod (m + 1) chips on each move

29 Chapter 4 69 Nim with l Piles Game: there are l > 1 piles of chips, containing n 1, n 2,..., n l chips Q: if you play first, what is your winning strategy? A (partial): consider l = 2 clearly, taking all the chips from one pile is a losing strategy so is taking all but one chip from one pile Why? Consider n 1 = 1, n 2 = 1: Consider n 1 = 2, n 2 = 2: Hypothesis? reducing the problem to the n 1 = 1, n 2 = 1 case (you lose) Except in what particular case?

30 Chapter 4 70 Nim with 2 Piles Hypothesis: for l = 2, having to choose when the two piles have the same number of chips means you are in a losing position Proof : if n 1 = n 2 = 3, your opponent duplicates your move, either reducing the problem to a previously solved case (where you lose), if you remove less than 3 chips, or by pseudo-induction, you are in a losing position whenever n 1 = n 2 In summary, if n 1 = n 2, you lose Q: if n 1 n 2, do you have a winning strategy? Q : If so, what is it?

31 Chapter 4 71 Nim with l > 2 Piles This is a more difficult problem But... an elegant solution exists: i.e., the bits in each position are XORed together E.g. with l = 3: n 1 = 9, n 2 = 12, n 3 = 3: The fact that the sum is 0 means the first player has a winning strategy in this case, remove 2 chips from the second pile: = 0000 Note that our strategy for l = 2 does exactly this

32 Chapter 5 Divide and Conquer

33 Chapter 5 72 Chapter 5: Divide and Conquer A More General Master Theorem Given a recurrence equation ( ) n T (n) = at c + f(n) where f(n) Θ(n d ) and d 0, Θ(n d ) T (n) Θ(n d log n) Θ(n log c a ) if a < c d if a = c d if a > c d In our previous version, f(n) = bn so d = 1, which simplifies the above equation to Θ(n) T (n) Θ(n log n) Θ(n log c a ) if a < c if a = c if a > c

34 Chapter 5 73 Mergesort Algorithm Mergesort: Mergesort(A[0..n-1]) if n > 1 B[] <- A[0..(n-1)/2] % integer division! C[] <- A[(n-1)/2+1..n-1] Mergesort(B[0..(n-1)/2]) Mergesort(C[0..n/2-1]) A[] <- Merge(B[0..(n-1)/2], C[0..n/2-1]) In the worst case, Merge() requires n 1 comparisons of data elements in any case, n elements have to be moved, so it is Ω(n) eh? in the more general master theorem f(n) Θ(n) If n = 2 k, the master theorem says Mergesort() is in Θ(n log n) This is very close to the theoretical minimum for comparison-based sorting algorithms what is the disadvantage of Mergesort()? GEQ?

35 Chapter 5 74 Quicksort Algorithm Quicksort: Quicksort(A[0..n-1]) if n > 1 rearrange A so that all values in A[0..s-1] are <= A[s] % partition 1 all values in A[s+1..n-1] are > A[s] % partition 2 Quicksort(A[0..s-1]) Quicksort(A[s+1..n-1]) Q: how do we do the rearrangement? there are many variations on this theme all(?) involve moving all values which are the pivot to locations in the array which are before all values > than the pivot (and making sure the pivot itself is at the end of the 1st partition)

36 Chapter 5 75 Quicksort: Choosing a Pivot How do we choose the pivot? just pick the first element of A just pick the last element of A We could pick the middle element of A pathological data sets can be constructed which cause this to perform badly exercise: construct such a pathological data set We could randomly choose an element of A We could pick 2m + 1 elements of A (how?), find the median of those elements, and use that as the pivot

37 Chapter 5 76 Quicksort: Partitioning Data Array Here is one technique to partition A with respect to the pivot a two-finger technique This technique assumes the pivot is in A[0] let i = 1 and j = n - 1 put left finger on A[i] put right finger on A[j] move it left until for some j we have A[j] <= A[0] swap A[i] with A[j] swap A[0] with A[j]

38 Chapter 5 77 Analysis of Quicksort: Worst Case Worst case: pivot is largest or smallest element T (0) = T (1) = 0 T (n) = n 1 + T (n 1) so T (2) = 1 + T (1) = = 1 T (3) = 2 + T (2) = = 3 T (4) = 3 + T (3) = = 6 T (5) = 4 + T (4) = 10 T (6) = 5 + T (5) = 15 Guess: T (n) = n 1 i=1 i = n(n 1) 2 So quicksort is Θ(n 2 ) in the worst case!

39 Chapter 5 78 Analysis of Quicksort: Best Case Best case: the two partitions are (roughly) the same size T (0) = T (1) = 0 T (n) = n T (n/2) We could solve this the hard way Or we could apply the master theorem and get T (n) Θ(n lg n) nice!

40 Chapter 5 79 Analysis of Quicksort: Average case (1) This is the tricky case to solve, but also the most interesting case (and the most significant real-world case) Assume that all permutations of the input are equally likely After division into two lists (and the pivot) we have lists of size i (0 i n 1) and n i 1 Applying the equally likely assumption and basic probability theory, we get (for n > 1) T (n) = n 1 + n 1 i=0 1 ( ) T (i) + T (n i 1) n

41 Chapter 5 80 Analysis of Quicksort: Average case (2) We want to solve: T (0) = T (1) = 0 T (n) = n 1 + n 1 i=0 1 ( ) T (i) + T (n i 1) n Note: The sum of those T (i) s is T (0) + T (1) + + T (n 1) The sum of those T (n i 1) s is T (n 1) + T (n 2) + + T (0) Thus T (n) = n n n 1 i=0 T (i) ( ) Now what? Guess: T (n) c n ln n n 1

42 Chapter 5 81 Analysis of Quicksort: Average case (3) To be shown: T (n) c n ln n n 1 The proof is by induction on n (surprise!) Base case (n = 1): c 1 ln 1 = 0 since T (1) = 0, the base case holds Substitute our guess (the induction hypothesis) into ( ): T (n) n n n 1 i=1 c i ln i Note lower index! How can we handle this sum? Note that the sum a 1 + a 2 + a 3 is equal to the total area of 3 rectangles of width 1 and heights (respectively) a 1, a 2, a 3 a 1 a 2 a 3

43 Chapter 5 82 Analysis of Quicksort: Average case (4) We can bound this area with an integral calculus can be useful! n T (n) n c x ln x dx note upper limit n 1 n 1 + 2c ( 1 n 2 n2 ln n 1 ) 4 n2 n 1 + c n ln n c n ( 2 c n ln n + n 1 c ) 1 (**) 2 To show T (n) c n ln n, all we need to show is that the second and third terms of (**) are 0 n(1 c/2) is 0 whenever 1 c/2 0, i.e., 2 c so choose c = 2 and we are done Alternative approach: subtract the summation formula for (n 1)T (n 1) from the summation formula for nt (n) and watch most of the terms vanish

44 Chapter 5 83 Analysis of Quicksort: Final Thoughts Intelligent choice of pivot can (usually) keep us from the Θ(n 2 ) situation Other improvements: recall: a Θ(n 2 ) algorithm can be better than a Θ(n lg n) algorithm for small values of n eliminate recursion (by clever programming) the textbook claims such improvements can decrease running time by 2025%

45 Chapter 5 84 Binary Search An efficient algorithm for searching in a sorted array two cases: sought element K is in array A, sought element K is not in array A left = 0 right = n-1 while left <= right mid = (left + right) / 2 % truncation to integer if K == A[mid] return mid if K < A[mid] right = mid - 1 % look in left half else left = mid + 1 % look in right half return -1 % flag for "not found" GEQ: Is this the optimum way to do the comparisons? Note: if the array is really big, the calculation of mid overflows!

46 Chapter 5 85 Analysis of Binary Search Count number of comparisons of data items (bogosity: counting the 3-way comparison as 1 comparison) worst case: the sought item is not in the array T (1) = 1 T (n) = 1 + T (n/2) solution (generalized master theorem (be careful!)): T (n) Θ(lg n) This is optimal for searching a sorted array Note that this is similar to the bisection algorithm for solving continuous equations of the form f(x) = 0

47 Chapter 5 86 Multiplying Large Integers There are many applications in which arithmetic of (arbitrarily) large numbers is required Example(s)? Consider the standard way of multiplying two n-digit integers by hand: a n 1 a n 2 a 1 a 0 b n 1 b n 2 b 1 b 0 c 0n d 0n 1 d 0n 2 d 01 d 00 c 1n d 1n 1 d 1n 2 d 11 d 10 c n 1n d n 1n 1 d n 1 1 d n 1 0 p 2n 1 p 2n 2 p n 1 p n 2 p 1 p 0 In total, there are n 2 one-digit multiplications and a similar number of additions Idea for long integers: break up integers into smaller pieces which can be multiplied with one machine instruction (e.g., n < 10 5 on a 32-bit machine) GEQ: is this still Θ(n 2 ) or is it now o(n 2 )?

48 Chapter 5 87 Multiplication: Divide and Conquer? Suppose we want to multiply n-digit numbers A and B; will it help to divide them into two pieces? write A = A 1 A 2 and B = B 1 B 2 where A = A 1 10 n/2 + A 2 and B = B 1 10 n/2 + B 2 we get AB = (A 1 10 n/2 + A 2 ) (B 1 10 n/2 + B 2 ) = A 1 B (n/2) + (A 1 B 2 + A 2 B 1 ) 10 n/2 + A 2 B 2 How many (single-digit) multiplications is this? n 2 n 2 2 n 2 n 2 for the first term for the second term in total, 4 n 2 n 2 = n2 No savings in this case! So what then?

49 Chapter 5 88 Multiplication: Divide and Conquer Try 2 As seen, we can write AB = A 1 B 1 10 n + (A 1 B 2 + A 2 B 1 ) 10 n/2 + A 2 B 2 and that with a little thought we can also write (A 1 + A 2 ) (B 1 + B 2 ) = A 1 B 1 + (A 1 B 2 + A 2 B 1 ) + A 2 B 2 rearranging, we get (A 1 B 2 + A 2 B 1 ) = (A 1 + A 2 ) (B 1 + B 2 ) A 1 B 1 A 2 B 2 But we already have computed A 1 B 1 and A 2 B 2, so we can compute (A 1 B 2 + A 2 B 1 ) with one n/2-digit multiplication instead of two (and four n/2-digit additions instead of one) So counting the number of single-digit multiplications for two n-digit numbers, we get T (1) = 1, T (n) = 3T (n/2) Solution: T (n) = 3 lg n = n lg 3 n gnuplot-multiplication!!!

50 Chapter 5 89 Fast Matrix Multiplication The straightforward algorithm to multiply two n n matrices is Θ(n 3 ) 1969: Strassen discovered that by dividing a matrix into 4 n/2 n/2 submatrices and doing some similar rearrangements, instead of using 8 multiplications of n/2 n/2 matrices, only 7 are needed This gives the recurrence equation T (1) = 1, T (n) = 7 T (n/2) for n > 1 The solution to this is T (n) = n lg 7 n 2.81 More complex algorithms have been found in 1987, Coppersmith and Winograd gave a n algorithm These algorithms have large/huge multiplicative constants not practical unless matrices are huge (but theoretically interesting)

51 Chapter 5 90 Closest-Pair Problem: Divide and Conquer Recall that the brute-force solution was O(n 2 ) Idea: divide points into two equal subsets S 1 and S 2 based upon their x coordinates (sort points using an O(n lg n) algorithm if needed) Recursively find the closest pair in each of S 1 and S 2 let d = min(d 1, d 2 ) We must now consider pairs of points (p 1, p 2 ) where p 1 S 1 and p 2 S 2 but... we need only consider pairs of points within distance d of the dividing line (call these C 1 and C 2 ) Key observation: for each p 1 in C 1, there are at most 6 points close enough in C 2 to be of interest! The running time is T (n) = 2 T (n/2) + M(n), where M(n) O(n) It can be shown that this problem is Ω(n log n)

52 Chapter 5 91 Closest-Pair Problem: As noted in the text, a key observation is the following: when considering each point in C 1 for points in C 2 closer than d, at most 6 points must be considered However, we must be able to efficiently find those 6 points The book talks about how we can sort the points to do this GEQ: what, exactly, is the textbook saying? GEQ: if we have to pre-sort (in O(n lg n) time) does this change the analysis? Why or why not?

53 Chapter 5 92 Convex Hull by Divide and Conquer ( Quickhull ) Notation: let P a P b denote the line segment from P a to P b Assume we have n points S = {P i : 1 i n}, where each P i = (x i, y i ) These points are sorted according to increasing order of their x coordinates; any ties are broken according to increasing y coordinate Choose the sorted list s first and last points P 1 and P n Divide S into S 1 and S 2, according to P 1 P n points to the left of P 1 P n are in S 1, points to the right of P 1 P n are in S 2 we will need an analytical test for left and right The convex hull of S is the union of the convex hulls of S 1 (the upper hull ) and S 2 (the lower hull ) Q: how can we efficiently divide S into S 1 and S 2?

54 Chapter 5 93 Upper Hull Construction If S 1 = Ø, the upper hull is just P 1 P n Otherwise, find point P S 1 which is furthest from P 1 P n Find sets S 1,1, the points to the left of P 1 P and S 1,2, the points to the left of P P n It can be shown that the points inside the triangle P 1 P P n cannot be on the upper hull (and thus we can ignore them from now on) there are no points to the left of both P 1 P and P P n Recursively compute the upper hull of {P 1 } S 1,1 {P } and {P } S 1,2 {P n } the concatenation of these upper hulls gives the upper hull of {P 1 } S 1 {P n }

55 Chapter 5 94 Quickhull: Testing Whether a Point is Left of a Line Let P 1 = (x 1, y 1 ), P 2 = (x 2, y 2 ) and P 3 = (x 3, y 3 ) Amazing fact you might not know: the area of the triangle bounded by P 1, P 2 and P 3 is equal to 1/2 of the magnitude of this determinant: x 1 y 1 1 x 2 y 2 1 x 3 y 3 1 = x 1(y 2 1 y 3 1) x 2 (y 1 y 3 ) + x 3 (y 1 y 2 ) The sign of this determinant is negative iff P 3 is to the left of the line P 1 P 2 Thus we can check in constant time whether a point is to the left of a line defined by two other points Quickhull is Θ(n 2 ) in the worst case

CSC Design and Analysis of Algorithms. Lecture 5. Decrease and Conquer Algorithm Design Technique. Decrease-and-Conquer

CSC Design and Analysis of Algorithms. Lecture 5. Decrease and Conquer Algorithm Design Technique. Decrease-and-Conquer CSC 8301- Design and Analysis of Algorithms Lecture 5 Decrease and Conquer Algorithm Design Technique Decrease-and-Conquer This algorithm design technique is based on exploiting a relationship between

More information

Computer Science 385 Analysis of Algorithms Siena College Spring Topic Notes: Divide and Conquer

Computer Science 385 Analysis of Algorithms Siena College Spring Topic Notes: Divide and Conquer Computer Science 385 Analysis of Algorithms Siena College Spring 2011 Topic Notes: Divide and Conquer Divide and-conquer is a very common and very powerful algorithm design technique. The general idea:

More information

Chapter 4. Divide-and-Conquer. Copyright 2007 Pearson Addison-Wesley. All rights reserved.

Chapter 4. Divide-and-Conquer. Copyright 2007 Pearson Addison-Wesley. All rights reserved. Chapter 4 Divide-and-Conquer Copyright 2007 Pearson Addison-Wesley. All rights reserved. Divide-and-Conquer The most-well known algorithm design strategy: 2. Divide instance of problem into two or more

More information

17/05/2018. Outline. Outline. Divide and Conquer. Control Abstraction for Divide &Conquer. Outline. Module 2: Divide and Conquer

17/05/2018. Outline. Outline. Divide and Conquer. Control Abstraction for Divide &Conquer. Outline. Module 2: Divide and Conquer Module 2: Divide and Conquer Divide and Conquer Control Abstraction for Divide &Conquer 1 Recurrence equation for Divide and Conquer: If the size of problem p is n and the sizes of the k sub problems are

More information

CS Data Structures and Algorithm Analysis

CS Data Structures and Algorithm Analysis CS 483 - Data Structures and Algorithm Analysis Lecture VI: Chapter 5, part 2; Chapter 6, part 1 R. Paul Wiegand George Mason University, Department of Computer Science March 8, 2006 Outline 1 Topological

More information

CSC Design and Analysis of Algorithms

CSC Design and Analysis of Algorithms CSC 8301- Design and Analysis of Algorithms Lecture 6 Divide and Conquer Algorithm Design Technique Divide-and-Conquer The most-well known algorithm design strategy: 1. Divide a problem instance into two

More information

CSC Design and Analysis of Algorithms. Lecture 6. Divide and Conquer Algorithm Design Technique. Divide-and-Conquer

CSC Design and Analysis of Algorithms. Lecture 6. Divide and Conquer Algorithm Design Technique. Divide-and-Conquer CSC 8301- Design and Analysis of Algorithms Lecture 6 Divide and Conquer Algorithm Design Technique Divide-and-Conquer The most-well known algorithm design strategy: 1. Divide a problem instance into two

More information

DIVIDE & CONQUER. Problem of size n. Solution to sub problem 1

DIVIDE & CONQUER. Problem of size n. Solution to sub problem 1 DIVIDE & CONQUER Definition: Divide & conquer is a general algorithm design strategy with a general plan as follows: 1. DIVIDE: A problem s instance is divided into several smaller instances of the same

More information

CSC Design and Analysis of Algorithms. Lecture 5. Decrease and Conquer Algorithm Design Technique. Decrease-and-Conquer

CSC Design and Analysis of Algorithms. Lecture 5. Decrease and Conquer Algorithm Design Technique. Decrease-and-Conquer CSC 8301- Design and Analysis of Algorithms Lecture 5 Decrease and Conuer Algorithm Design Techniue Decrease-and-Conuer This algorithm design techniue is based on exploiting a relationship between a solution

More information

Divide-and-Conquer. The most-well known algorithm design strategy: smaller instances. combining these solutions

Divide-and-Conquer. The most-well known algorithm design strategy: smaller instances. combining these solutions Divide-and-Conquer The most-well known algorithm design strategy: 1. Divide instance of problem into two or more smaller instances 2. Solve smaller instances recursively 3. Obtain solution to original

More information

Divide-and-Conquer. Dr. Yingwu Zhu

Divide-and-Conquer. Dr. Yingwu Zhu Divide-and-Conquer Dr. Yingwu Zhu Divide-and-Conquer The most-well known algorithm design technique: 1. Divide instance of problem into two or more smaller instances 2. Solve smaller instances independently

More information

Selection (deterministic & randomized): finding the median in linear time

Selection (deterministic & randomized): finding the median in linear time Lecture 4 Selection (deterministic & randomized): finding the median in linear time 4.1 Overview Given an unsorted array, how quickly can one find the median element? Can one do it more quickly than bysorting?

More information

The divide and conquer strategy has three basic parts. For a given problem of size n,

The divide and conquer strategy has three basic parts. For a given problem of size n, 1 Divide & Conquer One strategy for designing efficient algorithms is the divide and conquer approach, which is also called, more simply, a recursive approach. The analysis of recursive algorithms often

More information

Problem. Input: An array A = (A[1],..., A[n]) with length n. Output: a permutation A of A, that is sorted: A [i] A [j] for all. 1 i j n.

Problem. Input: An array A = (A[1],..., A[n]) with length n. Output: a permutation A of A, that is sorted: A [i] A [j] for all. 1 i j n. Problem 5. Sorting Simple Sorting, Quicksort, Mergesort Input: An array A = (A[1],..., A[n]) with length n. Output: a permutation A of A, that is sorted: A [i] A [j] for all 1 i j n. 98 99 Selection Sort

More information

Divide and Conquer. Algorithm Fall Semester

Divide and Conquer. Algorithm Fall Semester Divide and Conquer Algorithm 2014 Fall Semester Divide-and-Conquer The most-well known algorithm design strategy: 1. Divide instance of problem into two or more smaller instances 2. Solve smaller instances

More information

Computer Science 431 Algorithms The College of Saint Rose Spring Topic Notes: Decrease and Conquer

Computer Science 431 Algorithms The College of Saint Rose Spring Topic Notes: Decrease and Conquer Computer Science 431 Algorithms The College of Saint Rose Spring 2013 Topic Notes: Decrease and Conquer Our next class of algorithms are the decrease-and-conquer group. The idea here: 1. Reduce the problem

More information

Lecture 8: Mergesort / Quicksort Steven Skiena

Lecture 8: Mergesort / Quicksort Steven Skiena Lecture 8: Mergesort / Quicksort Steven Skiena Department of Computer Science State University of New York Stony Brook, NY 11794 4400 http://www.cs.stonybrook.edu/ skiena Problem of the Day Give an efficient

More information

EECS 2011M: Fundamentals of Data Structures

EECS 2011M: Fundamentals of Data Structures M: Fundamentals of Data Structures Instructor: Suprakash Datta Office : LAS 3043 Course page: http://www.eecs.yorku.ca/course/2011m Also on Moodle Note: Some slides in this lecture are adopted from James

More information

Lecture 2: Getting Started

Lecture 2: Getting Started Lecture 2: Getting Started Insertion Sort Our first algorithm is Insertion Sort Solves the sorting problem Input: A sequence of n numbers a 1, a 2,..., a n. Output: A permutation (reordering) a 1, a 2,...,

More information

CPS 616 TRANSFORM-AND-CONQUER 7-1

CPS 616 TRANSFORM-AND-CONQUER 7-1 CPS 616 TRANSFORM-AND-CONQUER 7-1 TRANSFORM AND CONQUER Group of techniques to solve a problem by first transforming the problem into one of: 1. a simpler/more convenient instance of the same problem (instance

More information

CS 6402 DESIGN AND ANALYSIS OF ALGORITHMS QUESTION BANK

CS 6402 DESIGN AND ANALYSIS OF ALGORITHMS QUESTION BANK CS 6402 DESIGN AND ANALYSIS OF ALGORITHMS QUESTION BANK Page 1 UNIT I INTRODUCTION 2 marks 1. Why is the need of studying algorithms? From a practical standpoint, a standard set of algorithms from different

More information

4.4 Algorithm Design Technique: Randomization

4.4 Algorithm Design Technique: Randomization TIE-20106 76 4.4 Algorithm Design Technique: Randomization Randomization is one of the design techniques of algorithms. A pathological occurence of the worst-case inputs can be avoided with it. The best-case

More information

Sorting is a problem for which we can prove a non-trivial lower bound.

Sorting is a problem for which we can prove a non-trivial lower bound. Sorting The sorting problem is defined as follows: Sorting: Given a list a with n elements possessing a total order, return a list with the same elements in non-decreasing order. Remember that total order

More information

The divide-and-conquer paradigm involves three steps at each level of the recursion: Divide the problem into a number of subproblems.

The divide-and-conquer paradigm involves three steps at each level of the recursion: Divide the problem into a number of subproblems. 2.3 Designing algorithms There are many ways to design algorithms. Insertion sort uses an incremental approach: having sorted the subarray A[1 j - 1], we insert the single element A[j] into its proper

More information

COMP Data Structures

COMP Data Structures COMP 2140 - Data Structures Shahin Kamali Topic 5 - Sorting University of Manitoba Based on notes by S. Durocher. COMP 2140 - Data Structures 1 / 55 Overview Review: Insertion Sort Merge Sort Quicksort

More information

Algorithms and Data Structures

Algorithms and Data Structures Algorithms and Data Structures Spring 2019 Alexis Maciel Department of Computer Science Clarkson University Copyright c 2019 Alexis Maciel ii Contents 1 Analysis of Algorithms 1 1.1 Introduction.................................

More information

CS 137 Part 8. Merge Sort, Quick Sort, Binary Search. November 20th, 2017

CS 137 Part 8. Merge Sort, Quick Sort, Binary Search. November 20th, 2017 CS 137 Part 8 Merge Sort, Quick Sort, Binary Search November 20th, 2017 This Week We re going to see two more complicated sorting algorithms that will be our first introduction to O(n log n) sorting algorithms.

More information

1 Probabilistic analysis and randomized algorithms

1 Probabilistic analysis and randomized algorithms 1 Probabilistic analysis and randomized algorithms Consider the problem of hiring an office assistant. We interview candidates on a rolling basis, and at any given point we want to hire the best candidate

More information

Module 2: Classical Algorithm Design Techniques

Module 2: Classical Algorithm Design Techniques Module 2: Classical Algorithm Design Techniques Dr. Natarajan Meghanathan Associate Professor of Computer Science Jackson State University Jackson, MS 39217 E-mail: natarajan.meghanathan@jsums.edu Module

More information

Scan and Quicksort. 1 Scan. 1.1 Contraction CSE341T 09/20/2017. Lecture 7

Scan and Quicksort. 1 Scan. 1.1 Contraction CSE341T 09/20/2017. Lecture 7 CSE341T 09/20/2017 Lecture 7 Scan and Quicksort 1 Scan Scan is a very useful primitive for parallel programming. We will use it all the time in this class. First, lets start by thinking about what other

More information

Algorithm Analysis. (Algorithm Analysis ) Data Structures and Programming Spring / 48

Algorithm Analysis. (Algorithm Analysis ) Data Structures and Programming Spring / 48 Algorithm Analysis (Algorithm Analysis ) Data Structures and Programming Spring 2018 1 / 48 What is an Algorithm? An algorithm is a clearly specified set of instructions to be followed to solve a problem

More information

n = 1 What problems are interesting when n is just 1?

n = 1 What problems are interesting when n is just 1? What if n=1??? n = 1 What problems are interesting when n is just 1? Sorting? No Median finding? No Addition? How long does it take to add one pair of numbers? Multiplication? How long does it take to

More information

Dr. Amotz Bar-Noy s Compendium of Algorithms Problems. Problems, Hints, and Solutions

Dr. Amotz Bar-Noy s Compendium of Algorithms Problems. Problems, Hints, and Solutions Dr. Amotz Bar-Noy s Compendium of Algorithms Problems Problems, Hints, and Solutions Chapter 1 Searching and Sorting Problems 1 1.1 Array with One Missing 1.1.1 Problem Let A = A[1],..., A[n] be an array

More information

Jana Kosecka. Linear Time Sorting, Median, Order Statistics. Many slides here are based on E. Demaine, D. Luebke slides

Jana Kosecka. Linear Time Sorting, Median, Order Statistics. Many slides here are based on E. Demaine, D. Luebke slides Jana Kosecka Linear Time Sorting, Median, Order Statistics Many slides here are based on E. Demaine, D. Luebke slides Insertion sort: Easy to code Fast on small inputs (less than ~50 elements) Fast on

More information

4. Sorting and Order-Statistics

4. Sorting and Order-Statistics 4. Sorting and Order-Statistics 4. Sorting and Order-Statistics The sorting problem consists in the following : Input : a sequence of n elements (a 1, a 2,..., a n ). Output : a permutation (a 1, a 2,...,

More information

CSCE 411 Design and Analysis of Algorithms

CSCE 411 Design and Analysis of Algorithms CSCE 411 Design and Analysis of Algorithms Set 3: Divide and Conquer Slides by Prof. Jennifer Welch Spring 2014 CSCE 411, Spring 2014: Set 3 1 General Idea of Divide & Conquer 1. Take your problem and

More information

SEARCHING, SORTING, AND ASYMPTOTIC COMPLEXITY. Lecture 11 CS2110 Spring 2016

SEARCHING, SORTING, AND ASYMPTOTIC COMPLEXITY. Lecture 11 CS2110 Spring 2016 1 SEARCHING, SORTING, AND ASYMPTOTIC COMPLEXITY Lecture 11 CS2110 Spring 2016 Time spent on A2 2 Histogram: [inclusive:exclusive) [0:1): 0 [1:2): 24 ***** [2:3): 84 ***************** [3:4): 123 *************************

More information

Sorting Shabsi Walfish NYU - Fundamental Algorithms Summer 2006

Sorting Shabsi Walfish NYU - Fundamental Algorithms Summer 2006 Sorting The Sorting Problem Input is a sequence of n items (a 1, a 2,, a n ) The mapping we want is determined by a comparison operation, denoted by Output is a sequence (b 1, b 2,, b n ) such that: {

More information

Multiple-choice (35 pt.)

Multiple-choice (35 pt.) CS 161 Practice Midterm I Summer 2018 Released: 7/21/18 Multiple-choice (35 pt.) 1. (2 pt.) Which of the following asymptotic bounds describe the function f(n) = n 3? The bounds do not necessarily need

More information

Test 1 Review Questions with Solutions

Test 1 Review Questions with Solutions CS3510 Design & Analysis of Algorithms Section A Test 1 Review Questions with Solutions Instructor: Richard Peng Test 1 in class, Wednesday, Sep 13, 2017 Main Topics Asymptotic complexity: O, Ω, and Θ.

More information

CSE373: Data Structure & Algorithms Lecture 21: More Comparison Sorting. Aaron Bauer Winter 2014

CSE373: Data Structure & Algorithms Lecture 21: More Comparison Sorting. Aaron Bauer Winter 2014 CSE373: Data Structure & Algorithms Lecture 21: More Comparison Sorting Aaron Bauer Winter 2014 The main problem, stated carefully For now, assume we have n comparable elements in an array and we want

More information

CSE 3101: Introduction to the Design and Analysis of Algorithms. Office hours: Wed 4-6 pm (CSEB 3043), or by appointment.

CSE 3101: Introduction to the Design and Analysis of Algorithms. Office hours: Wed 4-6 pm (CSEB 3043), or by appointment. CSE 3101: Introduction to the Design and Analysis of Algorithms Instructor: Suprakash Datta (datta[at]cse.yorku.ca) ext 77875 Lectures: Tues, BC 215, 7 10 PM Office hours: Wed 4-6 pm (CSEB 3043), or by

More information

COSC242 Lecture 7 Mergesort and Quicksort

COSC242 Lecture 7 Mergesort and Quicksort COSC242 Lecture 7 Mergesort and Quicksort We saw last time that the time complexity function for Mergesort is T (n) = n + n log n. It is not hard to see that T (n) = O(n log n). After all, n + n log n

More information

Divide and Conquer Sorting Algorithms and Noncomparison-based

Divide and Conquer Sorting Algorithms and Noncomparison-based Divide and Conquer Sorting Algorithms and Noncomparison-based Sorting Algorithms COMP1927 16x1 Sedgewick Chapters 7 and 8 Sedgewick Chapter 6.10, Chapter 10 DIVIDE AND CONQUER SORTING ALGORITHMS Step 1

More information

A 0 A 1... A i 1 A i,..., A min,..., A n 1 in their final positions the last n i elements After n 1 passes, the list is sorted.

A 0 A 1... A i 1 A i,..., A min,..., A n 1 in their final positions the last n i elements After n 1 passes, the list is sorted. CS6402 Design and Analysis of Algorithms _ Unit II 2.1 UNIT II BRUTE FORCE AND DIVIDE-AND-CONQUER 2.1 BRUTE FORCE Brute force is a straightforward approach to solving a problem, usually directly based

More information

CS Divide and Conquer

CS Divide and Conquer CS483-07 Divide and Conquer Instructor: Fei Li Room 443 ST II Office hours: Tue. & Thur. 1:30pm - 2:30pm or by appointments lifei@cs.gmu.edu with subject: CS483 http://www.cs.gmu.edu/ lifei/teaching/cs483_fall07/

More information

CSci 231 Final Review

CSci 231 Final Review CSci 231 Final Review Here is a list of topics for the final. Generally you are responsible for anything discussed in class (except topics that appear italicized), and anything appearing on the homeworks.

More information

/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Sorting lower bound and Linear-time sorting Date: 9/19/17

/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Sorting lower bound and Linear-time sorting Date: 9/19/17 601.433/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Sorting lower bound and Linear-time sorting Date: 9/19/17 5.1 Introduction You should all know a few ways of sorting in O(n log n)

More information

Topics. Trees Vojislav Kecman. Which graphs are trees? Terminology. Terminology Trees as Models Some Tree Theorems Applications of Trees CMSC 302

Topics. Trees Vojislav Kecman. Which graphs are trees? Terminology. Terminology Trees as Models Some Tree Theorems Applications of Trees CMSC 302 Topics VCU, Department of Computer Science CMSC 302 Trees Vojislav Kecman Terminology Trees as Models Some Tree Theorems Applications of Trees Binary Search Tree Decision Tree Tree Traversal Spanning Trees

More information

Unit-2 Divide and conquer 2016

Unit-2 Divide and conquer 2016 2 Divide and conquer Overview, Structure of divide-and-conquer algorithms, binary search, quick sort, Strassen multiplication. 13% 05 Divide-and- conquer The Divide and Conquer Paradigm, is a method of

More information

II (Sorting and) Order Statistics

II (Sorting and) Order Statistics II (Sorting and) Order Statistics Heapsort Quicksort Sorting in Linear Time Medians and Order Statistics 8 Sorting in Linear Time The sorting algorithms introduced thus far are comparison sorts Any comparison

More information

Sorting. There exist sorting algorithms which have shown to be more efficient in practice.

Sorting. There exist sorting algorithms which have shown to be more efficient in practice. Sorting Next to storing and retrieving data, sorting of data is one of the more common algorithmic tasks, with many different ways to perform it. Whenever we perform a web search and/or view statistics

More information

COE428 Lecture Notes Week 1 (Week of January 9, 2017)

COE428 Lecture Notes Week 1 (Week of January 9, 2017) COE428 Lecture Notes: Week 1 1 of 10 COE428 Lecture Notes Week 1 (Week of January 9, 2017) Table of Contents COE428 Lecture Notes Week 1 (Week of January 9, 2017)...1 Announcements...1 Topics...1 Informal

More information

Introduction to Algorithms

Introduction to Algorithms Lecture 1 Introduction to Algorithms 1.1 Overview The purpose of this lecture is to give a brief overview of the topic of Algorithms and the kind of thinking it involves: why we focus on the subjects that

More information

The complexity of Sorting and sorting in linear-time. Median and Order Statistics. Chapter 8 and Chapter 9

The complexity of Sorting and sorting in linear-time. Median and Order Statistics. Chapter 8 and Chapter 9 Subject 6 Spring 2017 The complexity of Sorting and sorting in linear-time Median and Order Statistics Chapter 8 and Chapter 9 Disclaimer: These abbreviated notes DO NOT substitute the textbook for this

More information

Introduction. e.g., the item could be an entire block of information about a student, while the search key might be only the student's name

Introduction. e.g., the item could be an entire block of information about a student, while the search key might be only the student's name Chapter 7 Sorting 2 Introduction sorting fundamental task in data management well-studied problem in computer science basic problem given an of items where each item contains a key, rearrange the items

More information

CHENNAI MATHEMATICAL INSTITUTE M.Sc. / Ph.D. Programme in Computer Science

CHENNAI MATHEMATICAL INSTITUTE M.Sc. / Ph.D. Programme in Computer Science CHENNAI MATHEMATICAL INSTITUTE M.Sc. / Ph.D. Programme in Computer Science Entrance Examination, 5 May 23 This question paper has 4 printed sides. Part A has questions of 3 marks each. Part B has 7 questions

More information

1 Definition of Reduction

1 Definition of Reduction 1 Definition of Reduction Problem A is reducible, or more technically Turing reducible, to problem B, denoted A B if there a main program M to solve problem A that lacks only a procedure to solve problem

More information

7. Sorting I. 7.1 Simple Sorting. Problem. Algorithm: IsSorted(A) 1 i j n. Simple Sorting

7. Sorting I. 7.1 Simple Sorting. Problem. Algorithm: IsSorted(A) 1 i j n. Simple Sorting Simple Sorting 7. Sorting I 7.1 Simple Sorting Selection Sort, Insertion Sort, Bubblesort [Ottman/Widmayer, Kap. 2.1, Cormen et al, Kap. 2.1, 2.2, Exercise 2.2-2, Problem 2-2 19 197 Problem Algorithm:

More information

Divide and Conquer 4-0

Divide and Conquer 4-0 Divide and Conquer 4-0 Divide-and-Conquer The most-well known algorithm design strategy: 1. Divide instance of problem into two or more smaller instances 2. Solve smaller instances recursively 3. Obtain

More information

Department of Computer Applications. MCA 312: Design and Analysis of Algorithms. [Part I : Medium Answer Type Questions] UNIT I

Department of Computer Applications. MCA 312: Design and Analysis of Algorithms. [Part I : Medium Answer Type Questions] UNIT I MCA 312: Design and Analysis of Algorithms [Part I : Medium Answer Type Questions] UNIT I 1) What is an Algorithm? What is the need to study Algorithms? 2) Define: a) Time Efficiency b) Space Efficiency

More information

Analyze the obvious algorithm, 5 points Here is the most obvious algorithm for this problem: (LastLargerElement[A[1..n]:

Analyze the obvious algorithm, 5 points Here is the most obvious algorithm for this problem: (LastLargerElement[A[1..n]: CSE 101 Homework 1 Background (Order and Recurrence Relations), correctness proofs, time analysis, and speeding up algorithms with restructuring, preprocessing and data structures. Due Thursday, April

More information

Lecture 5: Sorting Part A

Lecture 5: Sorting Part A Lecture 5: Sorting Part A Heapsort Running time O(n lg n), like merge sort Sorts in place (as insertion sort), only constant number of array elements are stored outside the input array at any time Combines

More information

CSE 373 Final Exam 3/14/06 Sample Solution

CSE 373 Final Exam 3/14/06 Sample Solution Question 1. (6 points) A priority queue is a data structure that supports storing a set of values, each of which has an associated key. Each key-value pair is an entry in the priority queue. The basic

More information

CS 303 Design and Analysis of Algorithms

CS 303 Design and Analysis of Algorithms Mid-term CS 303 Design and Analysis of Algorithms Review For Midterm Dong Xu (Based on class note of David Luebke) 12:55-1:55pm, Friday, March 19 Close book Bring your calculator 30% of your final score

More information

Divide-and-Conquer CSE 680

Divide-and-Conquer CSE 680 Divide-and-Conquer CSE 680 1 Introduction Given an instance x of a problem, the divide-and-conquer method works as follows. function DAQ(x) if x is sufficiently small or simple then solve it directly else

More information

CS473 - Algorithms I

CS473 - Algorithms I CS473 - Algorithms I Lecture 4 The Divide-and-Conquer Design Paradigm View in slide-show mode 1 Reminder: Merge Sort Input array A sort this half sort this half Divide Conquer merge two sorted halves Combine

More information

CS2223: Algorithms Sorting Algorithms, Heap Sort, Linear-time sort, Median and Order Statistics

CS2223: Algorithms Sorting Algorithms, Heap Sort, Linear-time sort, Median and Order Statistics CS2223: Algorithms Sorting Algorithms, Heap Sort, Linear-time sort, Median and Order Statistics 1 Sorting 1.1 Problem Statement You are given a sequence of n numbers < a 1, a 2,..., a n >. You need to

More information

Analysis of Algorithms. Unit 4 - Analysis of well known Algorithms

Analysis of Algorithms. Unit 4 - Analysis of well known Algorithms Analysis of Algorithms Unit 4 - Analysis of well known Algorithms 1 Analysis of well known Algorithms Brute Force Algorithms Greedy Algorithms Divide and Conquer Algorithms Decrease and Conquer Algorithms

More information

COMP 250 Fall recurrences 2 Oct. 13, 2017

COMP 250 Fall recurrences 2 Oct. 13, 2017 COMP 250 Fall 2017 15 - recurrences 2 Oct. 13, 2017 Here we examine the recurrences for mergesort and quicksort. Mergesort Recall the mergesort algorithm: we divide the list of things to be sorted into

More information

Run Times. Efficiency Issues. Run Times cont d. More on O( ) notation

Run Times. Efficiency Issues. Run Times cont d. More on O( ) notation Comp2711 S1 2006 Correctness Oheads 1 Efficiency Issues Comp2711 S1 2006 Correctness Oheads 2 Run Times An implementation may be correct with respect to the Specification Pre- and Post-condition, but nevertheless

More information

CS Divide and Conquer

CS Divide and Conquer CS483-07 Divide and Conquer Instructor: Fei Li Room 443 ST II Office hours: Tue. & Thur. 1:30pm - 2:30pm or by appointments lifei@cs.gmu.edu with subject: CS483 http://www.cs.gmu.edu/ lifei/teaching/cs483_fall07/

More information

Lecture 7. Transform-and-Conquer

Lecture 7. Transform-and-Conquer Lecture 7 Transform-and-Conquer 6-1 Transform and Conquer This group of techniques solves a problem by a transformation to a simpler/more convenient instance of the same problem (instance simplification)

More information

CPSC 311 Lecture Notes. Sorting and Order Statistics (Chapters 6-9)

CPSC 311 Lecture Notes. Sorting and Order Statistics (Chapters 6-9) CPSC 311 Lecture Notes Sorting and Order Statistics (Chapters 6-9) Acknowledgement: These notes are compiled by Nancy Amato at Texas A&M University. Parts of these course notes are based on notes from

More information

2/26/2016. Divide and Conquer. Chapter 6. The Divide and Conquer Paradigm

2/26/2016. Divide and Conquer. Chapter 6. The Divide and Conquer Paradigm Divide and Conquer Chapter 6 Divide and Conquer A divide and conquer algorithm divides the problem instance into a number of subinstances (in most cases 2), recursively solves each subinsance separately,

More information

Algorithms in Systems Engineering IE172. Midterm Review. Dr. Ted Ralphs

Algorithms in Systems Engineering IE172. Midterm Review. Dr. Ted Ralphs Algorithms in Systems Engineering IE172 Midterm Review Dr. Ted Ralphs IE172 Midterm Review 1 Textbook Sections Covered on Midterm Chapters 1-5 IE172 Review: Algorithms and Programming 2 Introduction to

More information

CSC 505, Spring 2005 Week 6 Lectures page 1 of 9

CSC 505, Spring 2005 Week 6 Lectures page 1 of 9 CSC 505, Spring 2005 Week 6 Lectures page 1 of 9 Objectives: learn general strategies for problems about order statistics learn how to find the median (or k-th largest) in linear average-case number of

More information

COSC 311: ALGORITHMS HW1: SORTING

COSC 311: ALGORITHMS HW1: SORTING COSC 311: ALGORITHMS HW1: SORTIG Solutions 1) Theoretical predictions. Solution: On randomly ordered data, we expect the following ordering: Heapsort = Mergesort = Quicksort (deterministic or randomized)

More information

Design and Analysis of Algorithms

Design and Analysis of Algorithms Design and Analysis of Algorithms CSE 5311 Lecture 8 Sorting in Linear Time Junzhou Huang, Ph.D. Department of Computer Science and Engineering CSE5311 Design and Analysis of Algorithms 1 Sorting So Far

More information

We will give examples for each of the following commonly used algorithm design techniques:

We will give examples for each of the following commonly used algorithm design techniques: Review This set of notes provides a quick review about what should have been learned in the prerequisite courses. The review is helpful to those who have come from a different background; or to those who

More information

Chapter 3:- Divide and Conquer. Compiled By:- Sanjay Patel Assistant Professor, SVBIT.

Chapter 3:- Divide and Conquer. Compiled By:- Sanjay Patel Assistant Professor, SVBIT. Chapter 3:- Divide and Conquer Compiled By:- Assistant Professor, SVBIT. Outline Introduction Multiplying large Integers Problem Problem Solving using divide and conquer algorithm - Binary Search Sorting

More information

MA/CSSE 473 Day 17. Divide-and-conquer Convex Hull. Strassen's Algorithm: Matrix Multiplication. (if time, Shell's Sort)

MA/CSSE 473 Day 17. Divide-and-conquer Convex Hull. Strassen's Algorithm: Matrix Multiplication. (if time, Shell's Sort) MA/CSSE 473 Day 17 Divide-and-conquer Convex Hull Strassen's Algorithm: Matrix Multiplication (if time, Shell's Sort) MA/CSSE 473 Day 17 Student Questions Exam 2 specification Levitin 3 rd Edition Closest

More information

Sorting: Given a list A with n elements possessing a total order, return a list with the same elements in non-decreasing order.

Sorting: Given a list A with n elements possessing a total order, return a list with the same elements in non-decreasing order. Sorting The sorting problem is defined as follows: Sorting: Given a list A with n elements possessing a total order, return a list with the same elements in non-decreasing order. Remember that total order

More information

Algorithm Efficiency & Sorting. Algorithm efficiency Big-O notation Searching algorithms Sorting algorithms

Algorithm Efficiency & Sorting. Algorithm efficiency Big-O notation Searching algorithms Sorting algorithms Algorithm Efficiency & Sorting Algorithm efficiency Big-O notation Searching algorithms Sorting algorithms Overview Writing programs to solve problem consists of a large number of decisions how to represent

More information

UNIT-2. Problem of size n. Sub-problem 1 size n/2. Sub-problem 2 size n/2. Solution to the original problem

UNIT-2. Problem of size n. Sub-problem 1 size n/2. Sub-problem 2 size n/2. Solution to the original problem Divide-and-conquer method: Divide-and-conquer is probably the best known general algorithm design technique. The principle behind the Divide-and-conquer algorithm design technique is that it is easier

More information

Presentation for use with the textbook, Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, Merge Sort & Quick Sort

Presentation for use with the textbook, Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, Merge Sort & Quick Sort Presentation for use with the textbook, Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015 Merge Sort & Quick Sort 1 Divide-and-Conquer Divide-and conquer is a general algorithm

More information

Unit 6 Chapter 15 EXAMPLES OF COMPLEXITY CALCULATION

Unit 6 Chapter 15 EXAMPLES OF COMPLEXITY CALCULATION DESIGN AND ANALYSIS OF ALGORITHMS Unit 6 Chapter 15 EXAMPLES OF COMPLEXITY CALCULATION http://milanvachhani.blogspot.in EXAMPLES FROM THE SORTING WORLD Sorting provides a good set of examples for analyzing

More information

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of MCA

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of MCA INTERNAL ASSESSMENT TEST 2 Date : 30/3/15 Max Marks : 50 Name of faculty : Sabeeha Sultana Subject & Code : ADA(13MCA41) Answer any five full question: 1.Illustrate Mergesort for the dataset 8,3,2,9,7,1,5,4.

More information

11/8/2016. Chapter 7 Sorting. Introduction. Introduction. Sorting Algorithms. Sorting. Sorting

11/8/2016. Chapter 7 Sorting. Introduction. Introduction. Sorting Algorithms. Sorting. Sorting Introduction Chapter 7 Sorting sorting fundamental task in data management well-studied problem in computer science basic problem given an array of items where each item contains a key, rearrange the items

More information

Question 7.11 Show how heapsort processes the input:

Question 7.11 Show how heapsort processes the input: Question 7.11 Show how heapsort processes the input: 142, 543, 123, 65, 453, 879, 572, 434, 111, 242, 811, 102. Solution. Step 1 Build the heap. 1.1 Place all the data into a complete binary tree in the

More information

Mergesort again. 1. Split the list into two equal parts

Mergesort again. 1. Split the list into two equal parts Quicksort Mergesort again 1. Split the list into two equal parts 5 3 9 2 8 7 3 2 1 4 5 3 9 2 8 7 3 2 1 4 Mergesort again 2. Recursively mergesort the two parts 5 3 9 2 8 7 3 2 1 4 2 3 5 8 9 1 2 3 4 7 Mergesort

More information

CS302 Topic: Algorithm Analysis #2. Thursday, Sept. 21, 2006

CS302 Topic: Algorithm Analysis #2. Thursday, Sept. 21, 2006 CS302 Topic: Algorithm Analysis #2 Thursday, Sept. 21, 2006 Analysis of Algorithms The theoretical study of computer program performance and resource usage What s also important (besides performance/resource

More information

Elementary maths for GMT. Algorithm analysis Part II

Elementary maths for GMT. Algorithm analysis Part II Elementary maths for GMT Algorithm analysis Part II Algorithms, Big-Oh and Big-Omega An algorithm has a O( ) and Ω( ) running time By default, we mean the worst case running time A worst case O running

More information

Sorting and Selection

Sorting and Selection Sorting and Selection Introduction Divide and Conquer Merge-Sort Quick-Sort Radix-Sort Bucket-Sort 10-1 Introduction Assuming we have a sequence S storing a list of keyelement entries. The key of the element

More information

CS1800 Discrete Structures Fall 2016 Profs. Aslam, Gold, Ossowski, Pavlu, & Sprague December 16, CS1800 Discrete Structures Final

CS1800 Discrete Structures Fall 2016 Profs. Aslam, Gold, Ossowski, Pavlu, & Sprague December 16, CS1800 Discrete Structures Final CS1800 Discrete Structures Fall 2016 Profs. Aslam, Gold, Ossowski, Pavlu, & Sprague December 16, 2016 Instructions: CS1800 Discrete Structures Final 1. The exam is closed book and closed notes. You may

More information

Trees. 3. (Minimally Connected) G is connected and deleting any of its edges gives rise to a disconnected graph.

Trees. 3. (Minimally Connected) G is connected and deleting any of its edges gives rise to a disconnected graph. Trees 1 Introduction Trees are very special kind of (undirected) graphs. Formally speaking, a tree is a connected graph that is acyclic. 1 This definition has some drawbacks: given a graph it is not trivial

More information

Chapter 7 Sorting. Terminology. Selection Sort

Chapter 7 Sorting. Terminology. Selection Sort Chapter 7 Sorting Terminology Internal done totally in main memory. External uses auxiliary storage (disk). Stable retains original order if keys are the same. Oblivious performs the same amount of work

More information

MA/CSSE 473 Day 12. Questions? Insertion sort analysis Depth first Search Breadth first Search. (Introduce permutation and subset generation)

MA/CSSE 473 Day 12. Questions? Insertion sort analysis Depth first Search Breadth first Search. (Introduce permutation and subset generation) MA/CSSE 473 Day 12 Interpolation Search Insertion Sort quick review DFS, BFS Topological Sort MA/CSSE 473 Day 12 Questions? Interpolation Search Insertion sort analysis Depth first Search Breadth first

More information

Divide and Conquer Algorithms

Divide and Conquer Algorithms CSE341T 09/13/2017 Lecture 5 Divide and Conquer Algorithms We have already seen a couple of divide and conquer algorithms in this lecture. The reduce algorithm and the algorithm to copy elements of the

More information

Plotting run-time graphically. Plotting run-time graphically. CS241 Algorithmics - week 1 review. Prefix Averages - Algorithm #1

Plotting run-time graphically. Plotting run-time graphically. CS241 Algorithmics - week 1 review. Prefix Averages - Algorithm #1 CS241 - week 1 review Special classes of algorithms: logarithmic: O(log n) linear: O(n) quadratic: O(n 2 ) polynomial: O(n k ), k 1 exponential: O(a n ), a > 1 Classifying algorithms is generally done

More information