Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It sounds as if you want an implementation of the following abstract data type.</p> <pre><code>insert(x, w): add item x to the collection with weight x select(p): return the item greater than a p weighted fraction of the items </code></pre> <p>For example, <code>select(0)</code> returns the minimum, <code>select(0.5)</code> returns the weighted median, and <code>select(1)</code> returns the maximum.</p> <p>I would implement this ADT in one of two ways. If selection is infrequent, I'd put the data in an array and use a linear-time selection algorithm, for O(1)-time inserts and O(n)-time selects. If selection is frequent, I'd use a binary search tree where each node stores the total weight in its subtree. For example, after</p> <pre><code>insert(2, 10) insert(1, 5) insert(3, 100) insert(4, 20) </code></pre> <p>the tree might look like</p> <pre><code> 2 (135) / \ / \ 1 (5) 4 (120) / / 3 (100) </code></pre> <p>Now, to find the weighted median, multiply <code>135</code> by <code>0.5</code> and get <code>67.5</code> as the desired "index". Starting at the root <code>2</code>, we find that <code>5</code> is less than <code>67.5</code>, so the item is not in the left subtree and we subtract <code>5</code> to obtain <code>62.5</code>, the index into the remainder of the tree. Since <code>135 - 120 = 15</code> is less than <code>62.5</code>, the median isn't <code>2</code>. We subtract <code>15</code> from <code>62.5</code> to obtain <code>47.5</code> and descend to <code>4</code>. At <code>4</code>, we find that <code>100</code> is greater than <code>47.5</code>, so <code>3</code> is the median.</p> <p>Assuming a balanced tree, the running time of both <code>insert</code> and <code>select</code> is <code>O(log n)</code>. If I were implementing from scratch, I'd probably opt for a splay tree.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload