-2

I am trying to find an algorithm that finds kth smallest element from unsorted array of size n at O(n) by using a function that returns the median of array of size n at O(n). I think I have to find a recursive function that has time complexity like cn+cn/2+cn/2^2+....+cn/2^j=O(n).

kiarashmo
  • 1
  • 3
  • Is the input array sorted ? – Dhruv Saraswat Jun 05 '22 at 06:26
  • No, the input array is unsorted. – kiarashmo Jun 05 '22 at 06:34
  • @Elliott Yes, I know median of medians algorithm but I don't think that algorithm helps me answer the question. If you know could you explaine it to me? – kiarashmo Jun 05 '22 at 08:14
  • Median-of-medians is not directly relevant here -- MoM is a way to find an approximate median in O(n) time, but that's not useful here because the question assumes the existence of an O(n) time exact-median-finding algorithm. – Paul Hankin Jun 05 '22 at 08:16
  • "Quickselect with a given O(n) median-finding function" is an intermediate step towards "Quickselect with an O(n) approximate-median-finding function like median-of-medians". Both are guaranteed O(n), but MoM is better for the absolute number of comparisons. – Paul Hankin Jun 05 '22 at 08:23

1 Answers1

0

You can use quickselect, using the provided O(n) median-finding algorithm.

Find the median in O(n) time, separate the array into three parts (smaller, equal and greater than the median), then recurse into the relevant part.

The complexity analysis is easy (compared to the standard randomized Quickselect algorithm). Finding the median and pivoting the array are both O(n), and then the size of array one recurses into has at most n/2 elements (by the definition of median). So the recurrence relation is T(n) = n + T(n/2) for which the solution is T(n) = O(n).

Paul Hankin
  • 54,811
  • 11
  • 92
  • 118
  • 1
    What your suggesting has the best average-time complexity, but isn't really an answer as the question is wanting to use a median function to do the job. – Elliott Jun 05 '22 at 07:50
  • @Elliott sorry, but I thought it obvious that when I say "find the median" I mean "find the median with the O(n) median function provided in the question". Perhaps it's not clear, so I will update the answer. – Paul Hankin Jun 05 '22 at 08:03