Maintaining a Sorted Sequence under Insertion
A sorted sequence can accept new items by locating their insertion position and then moving storage as needed.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace a repeated key
Insert 5 into 2, 5, 9. Choosing the position after the existing 5 preserves arrival order among these equal values. Stable ordering explains the resulting tie behavior.
Separate search and movement
A binary search can locate the insertion boundary quickly. In a contiguous array, moving later entries can still require time proportional to their count. Append and insert behavior describes the storage side of that tradeoff.[1]
Count movements separately from comparisons
Given an ordered array [2,5,9,12], inserting three uses search to find position one. In a contiguous array it still needs to shift five, nine and twelve. A logarithmic search bounds comparisons, while movement depends on distance to the end. See binary search by hand.
Insert 3 → find position 1 → shift 3 elements
Insert 13 → find position 5 → shift 0 after previous insert
The same search policy supports different movement costs
Relate the method to when consumers require sorted output
For a whole batch that becomes visible together, sorting once or sorting incoming records and merging can avoid repeated movements. If each insertion must become immediately visible in key order, maintain an ordered structure. Test batches in descending and ascending arrival order.