algorithmsortingmedianradix-sortmedian-of-medians

Find median of N 8-bit numbers


Given an array of N 8-bit numbers ( value 0-255)?

How to find the median?

I have tried radix sort and median of medians algorithms.

Is there a better way given the values of the numbers are between 0 and 255?


Solution

  • Use something similar to counting sort.

    This runs in O(n) time using O(1) space (which is asymptotically optimal).

    So something like: (pseudo-code)

    // Count the number of occurrences of each value.
    counts[256] = {0}
    for i = 0 to input.length
       counts[input[i]]++
    
    // Get the median.
    count = input.length
    sum = 0
    if count divisible by 2
       first = NaN
       for i = 0 to counts.length
          sum += counts[i]
          if first == NaN && sum >= count / 2
             first = i
          if sum >= count / 2 + 1
             median = (first + i) / 2
             break
    else
       for i = 0 to counts.length
          sum += counts[i]
          if sum >= (count + 1) / 2
             median = i
             break
    return median
    

    There are other ways to achieve the same time and space complexity (albeit a bit more complex than the above, and requiring you to modify the input array):