What would be the quickest way to insert values into the correct position in a sorted numpy array?
For example, I would like to insert every value of b
into a
:
a = [1,1,2,4,7,7,11,13,13,13,15,20,25,26,27,30,45,70]
b = [5,7,9,45]
I've tried looping through a
for each value of b
and inserting it that way. I've also tried the bisect_left
method:
for i in b:
a.insert(bisect_left(a,i),i)
Both methods are too slow as I have hundreds of thousands of data elements to go through.
Any ideas?
Insertion Sort is preferred for fewer elements. It becomes fast when data is already sorted or nearly sorted because it skips the sorted values. Efficiency: Considering average time complexity of both algorithm we can say that Merge Sort is efficient in terms of time and Insertion Sort is efficient in terms of space.
Solution. Use the associative container set , declared in <set> , which stores items in sorted order.
The insertion and deletion of elements in a sorted array executes at O(n), due to the need to shift all the elements following the element to be inserted or deleted; in comparison a self-balancing binary search tree inserts and deletes at O(log n).
You could use searchsorted
and insert
:
a = numpy.array([1,1,2,4,7,7,11,13,13,13,15,20,25,26,27,30,45,70])
b = numpy.array([5,7,9,45])
ii = numpy.searchsorted(a, b)
a = numpy.insert(a, ii, b)
let's note n = len(a) and m = len(b)
,
Now given possible values of n and m, you can determine which solution is best, but don't expect to do better than that
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With