0

I need to design an algorithm that finds the k'th smallest element in unsorted array using function that called "MED3": This function finds the n/3 (floor) and 2n/3 (ceil) elements of the array if it was sorted (very similar to median, but instead of n/2 it returns those values).

I thought about kind of partition around those 2 values, and than to continue like QuickSelect, but the problem is that "MED3" doesn't return indices of the 2 values, only the values.

for example, if the array is: 1, 2, 10, 1, 7, 6, 3, 4, 4 it returns 2 (n/3 value) and 4 (2n/3 value).

I also thought to run over the array and to take all the values between 2 and 4 (for example, in the given array above) to new array and then use "MED3" again, but can be duplicates (if the array is 2, 2, 2, 2, ..., 2 I would take all the elements each time).

Any ideas? I must use "MED3". * MED3 is like a black box, it runs in linear time.

Thank you.

Ran
  • 35
  • 1
  • 7
  • You want indices before the elements are placed at their correct place or after they are placed at their correct place? That is, indices of elements before calling partition or indices after calling partition? – sameerkn Jun 22 '16 at 06:01
  • Indices after calling partition (their correct indices if the array was sorted). he problem is the MED3 doesn't place them. – Ran Jun 22 '16 at 06:05

1 Answers1

0

I think you're on the right track, but instead of taking 2 to 4, I'd suggest removing the first n/3 values that are <= MED3.floor() and the first n/3 values that are >= MED3.ceil(). That avoids issues with too many duplicates. If two passes/cycle aren't too expensive, you can remove all values < MED3.floor() + up to a total of n/3 values = MED3.floor() (do the same for ceil())

then repeat until you are at the k'th smallest target.

dangVarmit
  • 5,641
  • 2
  • 22
  • 24