HW5 Solutions

# HW5 Solutions - Homework#5 Solutions 1 We are given a...

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
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Homework #5 Solutions 1. We are given a sorted array A [1 ..n ], composed of distinct integers (the values can be neg- ative). We want to determine if there is an index i such that A [ i ] = i . Give an O (log n ) algorithm to solve this problem, and justify its correctness. Solution If A [ n 2 ] = n 2 , we are done. If A [ n 2 ] < n 2 , then the left half of the array is irrelevant since the integers are distinct and strictly increasing, so recursively solve the problem on the right half of the array. Otherwise, recursively solve the problem on the left half of the array. The recur- rence relation for this problem will then be T ( n ) = T ( n 2 ) + Θ(1), which means the running time is Θ(log n ). 2. Suppose we’d like to implement a sorting variant where every element is compared only a small number of times. Note that while Merge Sort has O ( n log n ) comparisons, a particular element may be compared n or more times. (a) Devise a divide-and-conquer algorithm to merge two sorted arrays of length n , which guarantees that every element is included in at most O (log n ) comparisons. Hint: Use binary search to locate the median of one array in the other. Solution Look at middle element of the first array a [ n 2 ] (we’ll refer to this element as the pivot), then do a binary search in the second array until we find the location j such that b [ j- 1] ≤ a [ n 2 ] ≤ b [ j ]. Now we must recursively merge two smaller subproblems: we must]....
View Full Document

## This note was uploaded on 12/13/2010 for the course CSCI 570 at USC.

### Page1 / 2

HW5 Solutions - Homework#5 Solutions 1 We are given a...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online