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
Unformatted text preview: 1 CMPS 101 Summer 2009 Homework Assignment 1 Solutions 1. (1 Point) p.27: 2.22 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 pseudocode 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 bestcase and worstcase 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 29 first locates the minimum element in the subarray ] [ n i A L (lines 36), 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 29 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 27 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 27, the inner loop 46 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.
 Spring '09
 AgoreBack
 Sort

Click to edit the document details