I have a sequence of elements, say a1,a2,…,an. (n ~ 4*10^7)
The input will be mostly sorted. More specifically any element less than a_i will be either to the left, or very close to the right(~ 300 elements).
How can I sort this sequence efficiently?
You could do this using a heap of N elements where N is the maximum overlap (N=300 in your case).
Start with an empty heap.
For each element in the sequence:
Add element to the heap
If the heap has more than N elements, output (and remove from the heap) the smallest element
Finally output the remaining elements in the heap.
This will have complexity O(nlogN)