CS2800 - Data Structures and Algorithms - Homework 2
CS2800 - Data Structures and Algorithms - Homework 2
Note: For the problems that require designing an algorithm, write the algorithm precisely, provide the running time and prove its correctness. 1. What is the number of comparisons performed by insertion sort in the worst case? Is it possible to reduce the number of comparisons? If so, explain how. 2. Given a set {(x1 , y1 ), . . . , (xn , yn )} of n points in a Euclidean space, write an algorithm to nd the closest pair of points. 3. Prove that the following recursive algorithm for the multiplication of natural numbers is correct. Algorithm 1 multiply(y, z) if z = 0 then return(0) else if z is odd then return(multiply(2y, (z/2) )+y) else return(multiply(2y, (z/2) )) end if end if
4. Given a set S of n integers and another integer x, write an algorithm to determine whether or not there exist two elements in S whose sum is exactly x. 5. Write an algorithm to check whether the elements in an array A[1, . . . , n] are unique. ( Elements in the array A are in the range [1, . . . , n].) 6. Write a recursive algorithm to merge the given two sorted subarrays A[p, . . . , q] and A[q +1, . . . , r] into A[p, . . . , r]. 7. Let A[1, . . . , n] be an array of n distinct numbers. If i < j and A[i] > A[j], then the pair (i, j) is called an inversion of A. Write an algorithm that determines the number of inversions in any permutation of n elements. 8. Suppose that S and T are sorted arrays, each containing n distinct elements. Write an algorithm to nd the k th smallest of the 2n elements.