insort finds the spot in O(log n), then shifts everything after it in O(n)
Finding the spot is cheap. Making room isn't.
Predict
insort(a, 140) on a = [100, 130, 160, 220, 300]. How many items move to make room?
insort(a, x) finds the spot with bisect_right and inserts there. insort_left uses bisect_left. The search is O(log n). The insert isn't: every item after the spot moves over by one.
insort(a, 140) on a = [100, 130, 160, 220, 300]
012345
find the spot: a few looks
100130160220300
make room: 3 items move
100130160220300
put 140 in
100130140160220300
Python's docs warn about this too: the slow O(n) insert outweighs the O(log n) search. Measured on lists of random floats, one insort and one removal from the same spot, so two shifts:
n
insort and remove
bisect_left alone
append and pop
10,000
1.70 µs
91 ns
38 ns
100,000
18.75 µs
101 ns
37 ns
1,000,000
229.81 µs
118 ns
36 ns
Ten times the items, ten times the insort: O(n). The shift runs in C, so it's fast for its size. A few thousand inserts into a list of 10,000 take a few milliseconds.
Building a big sorted list one insort at a time is a different story. For 100,000 random floats, inserting each in place took 484.0 ms. Appending them all and sorting once took 12.9 ms.
When the items arrive in order, insort lands at the end every time, and nothing moves. That's the case the practice problem is built for.
In the editor, write insort_moves(a, x). It inserts 140, then a time that arrives in order, and prints what moved each time.
Pick an answer above to see the rest
Instructions
1
Write insort_moves(a, x): insert x into the sorted list a after any equal values, as insort does.
2
Return how many items moved to make room: every item after the spot.