Skip to content

Instantly share code, notes, and snippets.

@woodRock
Last active September 17, 2018 10:03
Show Gist options
  • Save woodRock/e7a4b981eb5e8701e1d749bf772cc6dd to your computer and use it in GitHub Desktop.
Save woodRock/e7a4b981eb5e8701e1d749bf772cc6dd to your computer and use it in GitHub Desktop.
Given an array of strictly the characters 'R', 'G', and 'B', segregate the values of the array so that all the Rs come first, the Gs come second, and the Bs come last. You can only swap elements of the array. Do this in linear time and in-place. For example, given the array ['G', 'B', 'R', 'R', 'B', 'R', 'G'], it should become ['R', 'R', 'R', 'G…
#!/usr/bin/env ruby
def sort(array)
order = ["R","G","B"]
res = Array.new(order.size()) { Array.new }
array.each { |c| res[order.index(c)] << c }
return res.flatten
end
def sort_proper(array)
array.each_with_index do |e, i|
next if i == 0
swap(array, i)
end
return array
end
def compare(this, other)
order = ["R","G","B"]
a = order.index(this)
b = order.index(other)
return b <=> a
end
def swap(array, idx)
valid = idx - 1 >= 0
while idx - 1 >= 0
larger = compare(array[idx], array[idx-1]) == 1
array[idx], array[idx-1] = array[idx-1], array[idx] if larger
idx -= 1
end
return array
end
unsorted = ['G', 'B', 'R', 'R', 'B', 'R', 'G']
puts sort_proper(unsorted)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment