- #1
TheMathNoob
- 189
- 4
Homework Statement
a Write an algorithm to find the median of three distinct integers a,b,c
b Describe D, the set of inputs for your algorithm, in light of the discussion in Section 1.4.3 following Example 1.9. This section discusses Average complexity for an algorithm which involves an understanding of random variables. Exercise 1.9 describes an array in which an algorithm must be written to find a certain value in the array. D describe the set of inputs. The book says that in this case the inputs can be categorized according to where in the array the value appears.
c How many comparisons does your algorithm do in the worst case? on the average?
d How many comparsions are necessary in the worst case to find the median of tree numbers? Justify your answer
Homework Equations
Average complexity=A(n) =∑Pr(I)t(I) the iterators for sigma is I∈Dn
t(I) is the number of basic operations performed by input I and Pr(I) represents the prob that I happens.
[/B]
The Attempt at a Solution
a)
int a;
int b;
int c;
int median;
if(a>b and a<c or a<b and a>c)
median =a;
else if(b>a and b<c or b<a and b>c)
median=b;
else
median=c;
b) Here I tried to categorize the events as the previous exercise.
Ii∈Dn
I1= the event in which the first comparison is true
I2= the event in which the second comparison is true and the previous ones are false (by logic)
I3= the event in which the third comparison is true and the previous ones are false (by logic)
I4= the event in which the forth comparison is true the previous ones are false
3) the compiler makes 4 comparisons in the worst case
Average=A(n)=∑Pr(Ii)t(i) the iterator for sigma is 1≤i≤4
Pr(Ii) is equally likely to occur in any case because in total there are 6 possible outcomes like a<b<c, b<a<c etc and just one outcome will make the Ii happens.
so
Pr(Ii)= 1/6 for 1≤i≤4
t(i)=i because if the compiler is reading the ith comparison then it should have read as well the previous comparisons.
A(n)=1/6*1+1/6*2+1/6*3+1/6*4=10/6=1.66
Note: This result will vary based on the compiler because compilers can take readings in different orders. In this case we are assuming that once the compiler sees the first comparison to be true then it doesn't look the second one.
Is all that right?
d) I did not get this part because to me, it looks the same as part c.
Last edited: