hw1 - remaining portion of the sequence each time. Write...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
1 CMPS 101 Summer 2009 Homework Assignment 1 1. (1 Point) p.27: 2.2-2 Consider sorting n numbers stored in array A by first finding the smallest element of A and exchanging it with the element in ] 1 [ A . Then find the second smallest element of A and exchange it with ] 2 [ A . Continue in this manner for the first 1 - n elements of A . Write pseudo-code for this algorithm, which is known as selection sort . What loop invariant does this algorithm maintain? Why does it need to run for only the first 1 - n elements, rather than for all n elements? Give the best-case and worst-case running times of selection sort in Θ -notation. 2. (1 Point) p.37: 2.3-5 Referring back to the searching problem (see Exercise 2.1-3), observe that if the sequence A is sorted, we can check the midpoint of the sequence against v and eliminate half of the sequence from further consideration. Binary search is an algorithm that repeats this procedure, halving the size of the
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: remaining portion of the sequence each time. Write pseudo-code, either iterative or recursive, for binary search. Argue that the worst-case running time of binary search is ) (lg n . 3. (4 Points) p.39: 2-4abcd Let ] 1 [ n A L be an array of n distinct numbers. If j i < and ] [ ] [ j A i A > , then the pair ) , ( j i is called an inversion of A . a. (1 Point) List the five inversions of the array ) 1 , 6 , 8 , 3 , 2 ( . b. (1 Point) What array with elements from the set {1, 2, 3, . ., n } has the most inversions? How many inversions does it have? c. (1 Point) What is the relationship between the running time of insertion sort and the number of inversions in the input array? Justify your answer. d. (1 Point) Give an algorithm that determines the number of inversions in any permutation of n elements in ) lg ( n n worst-case time. (Hint: Modify merge sort.)...
View Full Document

This note was uploaded on 12/03/2009 for the course CS CS101 taught by Professor Agoreback during the Spring '09 term at American College of Gastroenterology.

Ask a homework question - tutors are online