Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You could treat it like an insertion sort.</p> <p>Pseudocode:</p> <pre><code>let arr be one array with enough space for every item in a let b be another array with, again, enough space for all elements in a For each item in a: perform insertion sort on item into arr After performing the insertion, if there exists a number to the left, append that to b. Otherwise, append -1 to b return b </code></pre> <p>The main thing you have to worry about is making sure that you don't make the mistake of reallocating arrays (because it would reallocate n times, which would be extremely costly). This will be an implementation detail of whatever language you use (std::vector's reserve for C++ ... arr.reserve(n) for D ... ArrayList's ensureCapacity in Java...)</p> <p>A potential downfall with this approach compared to using a binary tree is that it's O(n^2) time. However, the constant factors using this method vs binary tree would make this faster for smaller sizes. If your n is smaller than 1000, this would be an appropriate solution. However, O(n log n) grows much slower than O(n^2), so if you expect a's size to be significantly higher and if there's a time limit that you are likely to breach, you might consider a more complicated O(n log n) algorithm.</p> <p>There are ways to slightly improve the performance (such as using a binary insertion sort: using binary search to find the position to insert into), but generally they won't improve performance enough to matter in most cases since it's still O(n^2) time to shift elements to fit.</p>
 

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