Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #! /usr/bin/env ruby
- # str is array of chars
- # pivot point is index in array to pivot on
- # returns type like `str`
- def quicksort(str, pivot_point)
- strlen = str.length
- # recursion terminating condition:
- return str if strlen <= 1
- # find the pivot character
- pivot_char = str[pivot_point]
- # make new arrays for left and right of pivot
- # note: I'm very much aware that this is not the most efficient method,
- # but it WILL make it easier to understand the concept of quicksort before
- # I proceed to cover the in-place version
- left = []
- right = []
- # go through all the elements, put the ones smaller than pivot_char on the left;
- # ...bigger on the right.
- for i in 0...strlen # exclusive range: 0 to one less than str's length
- next if i == pivot_point # skip over the pivot, we don't want to put it anywhere
- # because it'll already be in final position at the end of the function.
- if str[i] < pivot_char
- left << str[i]
- else
- right << str[i]
- end
- end
- # utilize recursion to sort the left and right arrays, until the partitions become
- # a singular-element array or an empty one.
- left = quicksort(left, rand(left.length))
- right = quicksort(right, rand(right.length))
- # overwrite the original str and drop the new stuff in, in order
- str = []
- str << left << pivot_char << right
- return str.flatten # flatten because we pushed an array, a character/one-letter-string, and another array
- # FYI: flatten makes a 2+D array 1D.
- end
- puts "give me a string"
- str = gets.chomp.split('')
- puts quicksort(str, rand(str.length)).join('')
Add Comment
Please, Sign In to add comment