1

I can't seem to understand how this works despite reading this - median of three values strategy

I understand that in quick sort, I can pick an arbitrary value to be my pivot and start from there. For a median of three quick sort, some online article said to pick the first, last and the middle values in the unsorted array and then pick the value that is the center of these 3 values (e.g 56, 12, 45 -45 will be picked). The example also shows it with 9 values, making it easy to pick the first, last and middle values.

What if the unsorted array is of 8 values only like 34, 66, 57, 45, 20, 98, 92, 41? Is my median value going to be 45 given that the first, last and middle values are 34, 45, 41 respectively?

Thanks.

user3118602
  • 553
  • 5
  • 19

1 Answers1

1

Is my median value going to be 45 given that the first, last and middle values are 34, 45, 41 respectively?

It will be 41, since that is the median of these three numbers.

In general, the method is picking three numbers according to some scheme, and taking the median as the current pivot.

If choosing the median of the first, middle, and last, there are some technicalities to consider, like an even sized array (as in your example), arrays of size less than three, etc. Any reasonable choice you do there will be fine.

Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
  • Thanks Ami. I don't really understand this sentence you mentioned `(so this method affects the current pivot and next ones each step)`. Does this means that the pivot will always be 41? As far as normal quicksort gues, the pivot changes. – user3118602 Aug 09 '20 at 08:20
  • @user3118602 I removed it - it is just adds confusion. Please ignore this point. – Ami Tavory Aug 09 '20 at 08:33
  • @user3118602 - when doing median of 3, since the compared values are already in cache, they could be optionally swapped if out of order, so in this case after doing median of three, {first, middle, last} = {35, 41, 45}. – rcgldr Aug 09 '20 at 21:30