Algorithm for min/max when order in row

117 Views Asked by At

I have 5 numbers which belongs to Z. I am trying to create an algorithm which gives the min and max from the set in only 6 iterations (the least we need to solve the problem).

The purpose in my method is set all numbers in a row from min to max, then the first is min and last is max.

for three numbers is like if a>b then we use a temporary variable d=b b=a a=d now i made a < b for sure. the next iteration is if b>c we do like above, then again a>c and last iteration is a>b again. in this method we get an order for any three numbers when 'a' is min and 'c' is max.

However, for 5 numbers I have an problem when I`m trying to make the numbers in row with only 6 iterations.

Any ideas?

1

There are 1 best solutions below

0
On BEST ANSWER

The problem with your approach is that you try to do more work than necessary(sorting instead of only finding max/min).

My idea is the following:

Let A[0] to A[4] be your 5 numbers. First you set min = max = A[0]. Now you compare A[1] and A[2]. The larger of these numbers you compare with max, the smaller you compare with min. Now you compare A[3] to A[4]. Again you now compare the larger of these numbers to max and the smaller to min. In this way you have exactly 6 comparisons.