Inserting numbers into a sorted array is a very common need.
Mathematica stack exchange for reference. Its priority queue appears extremely fast. https://mathematica.stackexchange.com/questions/224249/best-way-to-insert-element-into-an-ordered-list-at-the-correct-position
For J:
Using the built in sort /:~y
where y
is the sorted array -
examples: /:~ y,45.3
or /:~ y,3 6 67.7
would be the first choice.
Quicksort and bubblesort are much slower.
For a single insert rotating the number into the sorted list -
insert=: 4 : 0
NB. insert x into ordered array y
where=: x (< i. 1:) y
z=: (($y)-where)|.(where|.y),x
)
is around 2.5 times faster on y=.i.10000000
than /:~y
anything faster?
Binary search
I.
is the best you can do to find an element in a sorted array.[;.0
is the best you can do to extract a subarray.These are very fast on their own:
The bottleneck seems to be appending the new element thus copying the list to make the new list.
Other, more complicated, ways may offer better results, depending on what you need and what kind of input you have.