This preview shows pages 1–3. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: CS4820 Problem Set 4 Liyuan Gao lg342@cornell.edu Collaborators: Harris Karsh and Nicholas Beaumont 1 Algorithm: We note that merge sort is stable, and run merge sort on both A and B once by comparing their second element of each tuple, and again by comparing their first element of each tuple, resulting in a list of points ordered primarily by the first element of the tuple, and secondarily by the second elements of the tuple. Next, we take O(n) time to scan through both A and B to create a set of A[i] and B[i] such that A[i] and B[i] are sets of points that starts with i and is ordered by the second element. Next, we create an array and insert each instance of the second element into this array and append to the original with the index (current size) to create a pseudo lookup table. We note the property that the ys still preserves the original lexical ordering. A[1] = [(1,1), (1,4), , (1, m)] Algorithm Count (A, B): First, we divide A up into A[1 n/2] and A[n/2+1 n], and we scan along B to find a B[i] such that i > n/2 and divide B into two halves B[1 i] and B[i+1 m] too. Because i > n/2, we know that none of the elements in the A[n/2+1 n] set can be leq to any points in B[1 i]. Now we run Count(A[1 n/2], B[1 i]) and Count(A[n/2+1 n], B[i+1 m]) and record their count, and also that of merge(A[1 n/2], B[i+1 m]) and return that sum. If the length of A is just one, then, we simply return merge(A, B[i m]), where i is the first element such that i leq the first element of A. Since everything before i in B is smaller than the first element of A, then they obviously cannot be part of the count. If the length of A is zero, we just return 0, as there are zero inversions when A is nothing. Algorithm Merge (A, B): We require the precondition that all As have leq first elements than those in B. We want to sort the nearly sorted arrays A and B in O(n) time and cascadedly counting the number of orders. For each of the lookup index in A place it in the wouldbe spot on an array with the same length as the lookup array above. This gives us a way of ordering the As and Bs such that you may count the number of elements in A leq than that of B. count the number of elements in A leq than that of B....
View
Full
Document
This note was uploaded on 03/12/2012 for the course CS 4820 taught by Professor Kleinberg during the Spring '08 term at Cornell University (Engineering School).
 Spring '08
 KLEINBERG
 Algorithms, Sort

Click to edit the document details