U have 5 numbers , X1,X2,X3,X4,X5
With minimum no. of comparisons we have to find a median.
SWAP(X,Y) function is available to u .
It can be done in 6 comparisons.
Suppose, numbers are X1, X2, X3, X4, X5.
Comparison--->Bigger--->Smaller
X1 & X2 --------> X2 ------> X1
X3 & X4 --------> X3 ------> X4
(We will keep X5 hanging as of now.)
Now, here we sure that X2 and X3 comes in the first 3 biggest numbers. Hence we need to find out the 3rd number which comes in first 3 biggest numbers.
Hence, do the following comparison:
X1 & X4: Let us say bigger number is X1
Now, compare X1 and X5. Suppose it gives u X5 as bigger.
So, we can say X2, X3, X5 are the first 3 biggest numbers. Just find out the minimum of these 3 to get the median.
if numbers are like X2>X5>X1>X3>X4 (arranged in ascending order) then the above method is proved wrong....
I think that if we simply apply merge sort to these 5 numbers and after sorting the 3rd number in the array will be the median..
This method just requires lesser steps but there may be a method which is simpler and more efficient.![]()
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks