This preview shows pages 1–2. 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: Comp271 Written Assignment 1 Name: Gao, Yuan ID: 05734371 Email: cs gyx Problem 2 The method is like Mergesort. We will divide the array into parts and count the inversions of each part. Algorithm: Divide: Divide each array into 2 subarrays of the same size until each subarray contains only one element Conquer: Keep a counter to count the number of inversions. The initial value of the counter is 0 Keep 2 pointers pointer to the first element left subarray and the first element of the right subarray for each array. When combine 2 subarrays, we have to prepare a new array whose size is the sum of the sizes of the 2 subarrays Compare elements pointed by the pointers. 1. If the element in the left subarray is smaller, put it in the first empty position of the new array, move the left pointer to the next element 2. If the element in the right subarray is smaller, put it in the first empty position of the new array, move the right pointer to the next element 2.0Increase the counter by the number of elements left in the left subarray Until all the elements in the 2 subarrays have copied to the new array, then begin to process the new arrays If one subarray is empty, we can move all the left elements in the other subarray to the new array without comparisons or increasing the counter Thus when we combined and get the whole array which has the size of the original array, we can get the number of the inversions from the counter. Time complexity: Divide: Divide each array into 2 subarrays: O(n) Thus total time complexity in divide part is O(n) Conquer: Keep a counter: O(1) Keep 2 pointers: O(2) Maximum comparisons need: O(n) for each level, O(nlogn) in total Maximum pointersâ€™ move : O(n) for each level, O(nlogn) in total Increase the counter: O(n/2) for each level, O(n/2logn) in total Copy the elements in to the new array: O(n) for each level, O(nlogn) in total Thus total time complexity in conquer part is O(nlogn) Problem 3 (a) The method is like Mergesort. We will divide the array into parts and search for pairs whose sum is exactly x. Divide: Divide each array into 2 subarrays of the same size until each subarray contains only one element Conquer: First we combine 2 subarrays and then search for the pairs of elements Keep 2 pointers pointing to the first element left subarray and the first element of the right subarray for each array....
View
Full
Document
This note was uploaded on 10/10/2009 for the course COMP 271 taught by Professor Arya during the Spring '07 term at HKUST.
 Spring '07
 ARYA
 Sort

Click to edit the document details