Last active
October 29, 2017 17:15
-
-
Save bobfirestone/c5c129f08756a2da8569b914aa69f914 to your computer and use it in GitHub Desktop.
Ruby implementation of Trump Sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TrumpSort | |
def initialize(arr) | |
@arr = arr | |
@wall = nil | |
@sorted = [] | |
end | |
def sort | |
@arr.each {|n| looper(n)} | |
@sorted | |
end | |
def looper(n) | |
if @wall.nil? || n > @wall | |
@sorted << n | |
@wall = n | |
end | |
end | |
# or the entire thing as a class method | |
def self.sort(arr) | |
wall = nil | |
[].tap do |a| | |
arr.each do |n| | |
if wall.nil? || n > wall | |
wall = n | |
a << n | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Doing as an instance of TrumpSort and as a class method of TrumpSort.
Example:
arr = [1,3,2,5,4]
TrumpSort.new.sort(arr)
&TrumpSort.sort(arr)
both return[1,3,5]