Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.77 KB | None | 0 0
  1. from typing import List
  2. from heapq import heappush, heappop
  3.  
  4.  
  5. def sort_almost_sorted(a: List[int], k: int) -> List[int]:
  6. if not a:
  7. return []
  8.  
  9. length = len(a)
  10. if k >= length:
  11. return sorted(a) # apply built-in "timsort", designed to be quick on almost sorted lists
  12.  
  13. result = []
  14. min_heap = [] # maintain a min heap for a sliding window
  15. for slice_start in range(0, length, k + 1): # sliding window
  16. # push the next slice to min heap
  17. for index in range(slice_start, min(slice_start + k + 1, length)):
  18. heappush(min_heap, a[index])
  19.  
  20. result.append(heappop(min_heap))
  21.  
  22. # put the rest of the heap into the result
  23. for _ in range(len(min_heap)):
  24. result.append(heappop(min_heap))
  25.  
  26. return result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement