hw1solns - 1 CMPS 101 Summer 2009 Homework Assignment 1...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 1 CMPS 101 Summer 2009 Homework Assignment 1 Solutions 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. SelectionSort(A) 1. ] [ length A n ← 2. for 1 ← i to 1- n 3. i ← in index_of_m // find the index of the minimum element in ] [ n i A L 4. for 1 + ← i j to n 5. if ] in index_of_m [ ] [ A j A < 6. j ← in index_of_m 7. ] in index_of_m [ ] [ A i A ↔ // exchange element ] [ i A with ] in index_of_m [ A The loop 2-9 first locates the minimum element in the subarray ] [ n i A L (lines 3-6), then exchanges it with the element ] [ i A (line 7). Two loop invariants are maintained: (1) each element in subarray )] 1 ( 1 [- i A L is less than or equal to each element in ] [ n i A L , and (2) the subarray )] 1 ( 1 [- i A L is sorted in increasing order. The correctness of SelectionSort follows from these two invariants, for when loop 2-9 is complete, invariant (1) implies that ] [ n A is greater than or equal to each element in the subarray )] 1 ( 1 [- n A L , which is itself sorted by invariant (2). Hence the full array ] 1 [ n A L is at that point sorted. This explains why it is unnecessary to continue loop 2-7 until n i = . The subarray ] [ n A is already sorted, since it contains only one element. Observe that on the th i iteration of loop 2-7, the inner loop 4-6 executes exactly ) ( i n- times, and on each such execution, exactly one array comparison is performed (line 5). Thus in all cases (best, worst, average) the number of comparisons done by SelectionSort is 2 ) 1 ( ) ( 1 1 1 1- = =- ∑ ∑- =- = n n i i n n i n i ....
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.

Page1 / 5

hw1solns - 1 CMPS 101 Summer 2009 Homework Assignment 1...

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

View Full Document Right Arrow Icon
Ask a homework question - tutors are online