Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is a solution that takes O(n log n) time, O(n) auxiliary space, and exactly n MoveToFront operations.</p> <p>Given the input array, A, Make a second array, B, with value/index pairs, like so...</p> <pre><code>7 8 9 11 1 10 -&gt; (7 0) (8 1) (9 2) (11 3) (1 4) (10 5) [this step takes O(n) time and O(n) space] </code></pre> <p>then sort B in descending order of the value of each pair...</p> <pre><code>(7 0) (8 1) (9 2) (11 3) (1 4) (10 5) -&gt; (11 3) (10 5) (9 2) (8 1) (7 0) (1 4) [this step takes O(n log n) time] </code></pre> <p>prepare a binary search tree, T.</p> <p>Now for each element in B do the following...</p> <pre><code>Let I be the index of this element. Let V be the sum of I and the number of elements in T that are greater than I. Do a MoveToFront operation on the Vth element of A. Add I to T. [Both of the operations on T take O(log n) time] </code></pre> <p>Here is this algorithm working on your example array</p> <pre><code>(11 3) I := 3 V := 3 + 0 = 3 MoveToFront(3): 7 8 9 11 1 10 -&gt; 11 7 8 9 1 10 T: () -&gt; (3) (10 5) I := 5 V := 5 + 0 = 5 MoveToFront(5): 11 7 8 9 1 10 -&gt; 10 11 7 8 9 1 T: (3) -&gt; (3 5) (9 2) I := 2 V := 2 + 2 = 4 MoveToFront(4): 10 11 7 8 9 1 -&gt; 9 10 11 7 8 1 T: (3 5) -&gt; (2 3 5) (8 1) I := 1 V := 1 + 3 = 4 MoveToFront(4): 9 10 11 7 8 1 -&gt; 8 9 10 11 7 1 T: (2 3 5) -&gt; (1 2 3 5) (7 0) I := 0 V := 0 + 4 = 4 MoveToFront(4): 8 9 10 11 7 1 -&gt; 7 8 9 10 11 1 T: (1 2 3 5) -&gt; (0 1 2 3 5) (1 4) I := 4 V := 4 + 1 = 5 MoveToFront(5): 7 8 9 10 11 1 -&gt; 1 7 8 9 10 11 T: (0 1 2 3 5) -&gt; (0 1 2 3 4 5) </code></pre> <p>I imagine you can find ways to sort these arrays that use fewer than n MoveToFront/Back operations, but I don't think you can find those in less than O(n log n) time. If those operations are slow, though, then it might be worth using an algorithm that takes more time to plan so you can do fewer of those operations.</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. 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.
 

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