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: A LGORITHMS S AMPLE S OLUTIONS — S ORTING 1 Sorting Problem 1: (Insertion sort) Insertion sort can be expressed as a recursive procedure as follows. In order to sort A [1 ..n ] , we recursively sort A [1 ..n 1] and then insert A [ n ] into the sorted array A [1 ..n 1] . Write a recurrence for the running time of this recursive version of insertion sort. Proof: Let T ( n ) be the time needed to sort an array of n elements using this recursive version of insertion sort. In the recursive step of this version, the same algorithm is run on an array of n 1 elements, and there is an additional step of at most n 1 comparison in order to insert the last element input in the sorted array of n 1 elements. Then the recurrence for the running time is T ( n ) = T ( n 1) + O ( n ) . Problem 2: (Twosum) Given two sets S 1 and S 2 (each of size n ), and a number x , describe an O ( n lg n ) algorithm for finding whether there exists a pair of elements, one from S 1 and one from S 2 , that add up to x . Proof: (Solution 1) A Θ( n 2 ) algorithm would entail examining each element y 1 in S 1 and determining if there is an element y 2 in S 2 such that y 1 + y 2 = x . FINDSUM( S 1 , S 2 , x ) 1. for y i ∈ S 1 , 2. for y j ∈ S 2 , 3. if y i + y j = x then return ( y i , y j ) Proof: (Solution 2) A more efficient solution takes advantage of sorting as a subroutine. First, we sort the numbers in S 2 . Next, we loop through each element y i in S 1 and then do a binary search on the sorted S 2 for x y i . FINDSUM( S 1 , S 2 , x ) 1. M ERGESORT ( S 2 ) 2. for y i ∈ S 1 , 3. y j = B INARY S EARCH ( S 2 , x y i ) 4. if ( y j 6 = notfound) then return ( y i , y j ) The M ERGE S ORT takes time Θ( n lg n ) . For each element in S 1 the B INARY S EARCH on S 2 will take O (lg n ) . Since this binary search is done n times the for loop requires O ( n lg n ) worstcase time. The worstcase time for the entire algorithm is also O ( n lg n ) . 1 Problem 3: (Convex polygon to cover the points) Given n points in two dimensions, find the convex polygon of smallest area that contains them all. Proof: Let ( x 1 , y 1 ) , .., ( x n , y n ) be n points in two dimensions. Very often in geometrical problems, it is a good idea to sort the points by one or both coordinates. In our problem, we sort the points ( x i , y i ) such that either x i < x i +1 or x i = x i +1 and y i ≤ y i +1 . This sorting assures us that the points are visited from the left to the right and from the bottom to the top when the counter increases from 1 to n ....
View
Full
Document
This note was uploaded on 03/16/2010 for the course CSE 101 taught by Professor Staff during the Winter '08 term at UCSD.
 Winter '08
 staff
 Sort, Insertion Sort

Click to edit the document details