Quiz3-Sol - In general, the program has to perform 2(n-1)...

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

View Full Document Right Arrow Icon
Solution for Quiz 3 COT 3100, Spring 2010 The following program finds the max and min of an input array --------------------------------------------------------------------------------------------- Input: Array a[] with n elements Output: The maximum and minimum elements of the given array --------------------------------------------------------------------------------------------- max = a[1]; min = a[1]; for(int i=2;i<=n;i++) { if (max < a[i]) max = a[i]; (*) if (min > a[i]) min = a[i]; (**) } return max, min; ------------------------------------------------------------------------------------------------
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: In general, the program has to perform 2(n-1) comparisons inside the loop. In the worst case for finding max (i.e., the input array is already in increasing order), the program needs (n-1) assignments in (*) and no assignment in (**) since the worst case of max is the best case of min and vice versa. The same argument applies for the worst case for finding min. Therefore, the total number of comparisons and assignments in the worst case is: 2(n-1) + (n-1) = 3n 3....
View Full Document

Ask a homework question - tutors are online