Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from typing import List
- from heapq import heappush, heappop
- def sort_almost_sorted(a: List[int], k: int) -> List[int]:
- if not a:
- return []
- length = len(a)
- if k >= length:
- return sorted(a) # apply built-in "timsort", designed to be quick on almost sorted lists
- result = []
- min_heap = [] # maintain a min heap for a sliding window
- for slice_start in range(0, length, k + 1): # sliding window
- # push the next slice to min heap
- for index in range(slice_start, min(slice_start + k + 1, length)):
- heappush(min_heap, a[index])
- result.append(heappop(min_heap))
- # put the rest of the heap into the result
- for _ in range(len(min_heap)):
- result.append(heappop(min_heap))
- return result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement