Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2019
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. ##
  2. # A quick sort implementation I made for fun in Ruby.
  3. def quick_sort(values)
  4. return values if values.size < 2
  5. pivot_index = values.size - 1
  6. pivot_value = values[pivot_index]
  7. curr_index = 0
  8. (values.size - 1).times do
  9. curr_value = values[curr_index]
  10. # less than or equal, leave the item where it is
  11. if curr_value <= pivot_value
  12. curr_index += 1
  13. elsif curr_value > pivot_value
  14. # bump everything over one, including pivot
  15. (pivot_index - curr_index).times do |i|
  16. values[curr_index + i] = values[curr_index + i + 1]
  17. end
  18. values[pivot_index] = curr_value
  19. pivot_index -= 1
  20. end
  21. end
  22.  
  23. smaller = pivot_index == 0 ? [] : values[0..pivot_index - 1]
  24. larger = values[pivot_index + 1..values.size]
  25.  
  26. [*quick_sort(smaller), pivot_value, *quick_sort(larger)]
  27. end
  28.  
  29. # quick dirty tests
  30. [
  31. [5,2,7,1,3,-5,13,4],
  32. [1,2,3,2,1],
  33. ].map do |test|
  34. puts "Sorting #{test}"
  35. puts "Sorted #{quick_sort(test)}"
  36. quick_sort(test)
  37. end
  38. # first move: 2, 1, 4, 5
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement