Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can solve your problem like that:</p> <p>You can find the median in <code>O(n)</code>, w.g. using the <code>O(n)</code> <a href="http://www.cplusplus.com/reference/algorithm/nth_element/" rel="nofollow">nth_element algorithm</a>.</p> <p>You loop through all elements substutiting each with a pair: <code>&lt;the absolute difference to the median&gt;, &lt;element's value&gt;</code>. Once more you do nth_element with <code>n</code> = <code>k</code>. after applying this algorithm you are guaranteed to have the <code>k</code> smallest elements in absolute difference first in the new array. You take their indices and DONE!</p> <p>Your algorithm, on the other hand uses sorting, and this makes it <code>O(nlogn)</code>.</p> <p><strong>EDIT</strong>: The requested example:</p> <p>Let the array be <code>[14, 6, 7, 8, 10, 13, 21, 16, 23]</code>.</p> <ul> <li>After the step for finding the median it will be reordered to, say: <code>[8, 7, 9, 10, 13, 16, 23, 14, 21]</code>, notice that the array is not sorted, but still the median (13) is exactly in the middle.</li> <li>Now let's do the pair substitution that got you confused: we create a new array of pairs: <code>[&lt;abs(14-13), 14&gt;, &lt;abs(6-13), 6&gt;, &lt;abs(7-13), 7&gt;, &lt;abs(8-13), 8&gt;, &lt;abs(10-13), 10&gt;, &lt;abs(13-13), 13&gt;, &lt;abs(21-13), 21&gt;, &lt;abs(16-13), 16&gt;, &lt;abs(23-13), 23&gt;</code>. Thus we obtain the array: <code>[&lt;1, 14&gt;, &lt;7, 6&gt;, &lt;6, 7&gt;, &lt;5, 8&gt;, &lt;3, 10&gt;, &lt;0, 13&gt;, &lt;8, 21&gt;, &lt;3, 16&gt;, &lt;10, 23&gt;</code></li> <li>If e.g. <code>k</code> is 4 we make once more nth_element(using the first element of each pair for comparisons) and obtain: <code>[&lt;1, 14&gt;, &lt;3, 16&gt;, &lt;0, 13&gt;, &lt;3, 10&gt;, &lt;8, 21&gt;, &lt;7, 6&gt;, &lt;10, 23&gt;, &lt;6, 7&gt;, &lt;5, 8&gt;]</code> so the numbers you search for are the second elements of the first 4 pairs: <code>14</code>, <code>16</code>, <code>13</code> and <code>10</code></li> </ul>
    singulars
    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. 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