Is it possible to divide a sequence of numbers into two groups based on the median value without sorting?

Is there an algorithm for splitting a sequence of random numbers into two groups based on the median value determined on the fly (without sorting them)?

Ex. If I have a sequence of 2-3-6-7-1-4-5, the result will be two divided groups:

A) 1 2 3

B) 5 6 7

Average value: 4

+3
source share
4 answers

Yes, this can be done in O (n) .

, , O (n), . , O (n)?

, quicksort, , , , (.. , ⌈n/2⌉). quicksort (,

0

( ) .

+3

BFPRT (Blum-Floyd-Pratt-Rivest-Tarjan) ( wiki) , .. O(n).

"" O , O(n log n) .

0

, (n/2) th (n/2) th . SO.

, , , , .


, , (n/2): " " (S) " " ( L), :

  • , e.
  • S, S .
  • S , (S | e) ( ) ( impedlemented S, , e, , e, ) L. S, e S, .
  • L , (L | e) , e L, e .

I believe this is O (n) time; someone correct me if I am wrong. The worst scenario I could imagine was sorting the original sequence in descending order.

ruby implementation (with lots of inactivity shortcuts):

def split_into_halves to_split
  s = []
  l = []
  medianlimit = to_split.size/2
  for e in to_split
    if s.size < medianlimit
      s.push(e)
    else

      if s.max >= n
        max = s.max
        s.delete max
        s.push(e)
      else
        max = e
      end

      if l.size < medianlimit
        l.push(max)
      elsif l.max >= max
        l.delete l.max
        l.push(max)
      end

    end
  end

  return [s,l]
end

k = [2,3,6,7,1,4,5]
split_into_halves(k) #=> [[2,3,1],[6,4,5]]
-1
source

Source: https://habr.com/ru/post/1750569/


All Articles