def sort_almost_sorted(A, k):
h = list(A[:k+1])
heapq.heapify(h)
result = []
for a in A[k+1:]:
x = heapq.heapreplace(h, a)
result.append(x)
while len(h) > 0:
result.append(heapq.heappop(h))
return result