Advertisement
Guest User

Untitled

a guest
May 30th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.68 KB | None | 0 0
  1. """
  2. Selection algorithms
  3.  
  4. python implementaiton of quickselect and heapselect
  5.  
  6. quickselect does not guarantee the selection to be sorted and has a O(n)
  7. complexity, while heapselect sorts the selection in O(n*log(k))
  8. """
  9.  
  10. import random
  11. import heapq
  12.  
  13. def quickselect(l, k):
  14. pivot = random.choice(l)
  15. pivots = [x for x in l if x == pivot]
  16. left = [x for x in l if x < pivot]
  17. right = [x for x in l if x > pivot]
  18.  
  19. if len(right) > k:
  20. return quickselect(right, k)
  21. if len(right) + len(pivots) >= k:
  22. return right + pivots[:(k - len(right))]
  23. return quickselect(left, k - len(right) - len(pivots)) + pivots + right
  24.  
  25.  
  26. def heapselect(l, k):
  27. return heapq.nlargest(k, l)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement