Find median out of 5 numbers

By | December 24, 2014
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  

In quickselect, it requires to find the median out of the group of 5 numbers. Here I found a way from stackoverflow link. It requires 6 comparisons.

  1. Start a mergesort with the first 4 elements and order each pair (2 comparisons)
  2. Compare the two lower ones of each pair and eliminate the lowest one from the possibilities (3 comparisons)
  3. Add in the 5th number set aside to the number without a pair and compare the two (4 comparisons)
  4. Compare the two lowest of the two new pairs and eliminate the lower one (5 comparisons)
  5. Compare the one by itself and the lower of the last pair and the lower number is the medianThe possible median is within the parentesis