Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #! /usr/bin/env ruby
- class Array
- def mergesort
- return self if length <= 1
- if length == 2 # we swap if the length is two and the "two array" is unsorted still
- if (self[0] > self[1])
- self[0],self[1] = self[1],self[0]
- end
- return self
- end
- left = self[0...self.length/2].mergesort
- right = self[self.length/2...self.length].mergesort
- arr = []
- while(!left.empty? && !right.empty?)
- if left.first < right.first
- arr << left.first
- left.shift #i remove the first element from left after it gets merged
- # it's so i can keep comparing using left/right.first
- else
- arr << right.first
- right.shift # remove first element from right after merging it
- end
- end
- if !left.empty?
- arr += left # if the left array is not yet fully merged, tack on the remaining values
- elsif !right.empty?
- arr += right # if the right array is not yet fully merged, tack on remaining values
- end
- return arr
- end
- end
- puts "give me a string"
- str = gets.chomp.split('')
- strlen = str.length
- puts str.mergesort.join('')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement