Advertisement
wavec022

quicksort

Jan 29th, 2021 (edited)
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.76 KB | None | 0 0
  1. Quicksort / Quickselect?
  2.  
  3. Quicksort
  4.  
  5. - Input is a list
  6. - choose the first element as the pivot
  7. - split the rest of the list into things smaller than the pivot and bigger than the pivot (equals on either side)
  8. - recursively sort the sides
  9. - put them together
  10.  
  11. def quicksort(list: List[Int]): List[Int] = {
  12. if(list.length <= 1) list
  13. else {
  14. val i = (list.length/2)
  15. return quicksort(list.take(i)) ::: quicksort(list.drop(i))
  16. }
  17. }
  18.  
  19. that actually doesn't work though
  20.  
  21. =====
  22.  
  23. def quicksort(list: List[Int]): List[Int] = {
  24. if(list.length <= 1) list
  25. else {
  26. val pivot = list.head
  27. val (smaller,bigger) = list.tail.partition(_ < pivot)
  28. quicksort(smaller) ::: pivot :: quicksort(bigger)
  29. }
  30. }
  31.  
  32. T(n) = 2*T(n/2) + n ==> O(nlogn)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement