Skip to content

Instantly share code, notes, and snippets.

@gbrl
Forked from davidvandusen/sort.rb
Last active April 26, 2016 22:19
Show Gist options
  • Save gbrl/1c4c0dccc9deb2b6356f87ea3b8d93e8 to your computer and use it in GitHub Desktop.
Save gbrl/1c4c0dccc9deb2b6356f87ea3b8d93e8 to your computer and use it in GitHub Desktop.
# Sort the array from lowest to highest
def sort(arr)
a_length = arr.length
return arr if a_length == 1
return [] if a_length == 0
keep_going = true
while keep_going do
flagged = false
arr.each_with_index do |num,index|
unless (index + 1 == arr.length ) # Can't compare last number with next one since it doesn't exist.
flag = (num <=> arr[index+1])
if flag == 1 # If the first number is smaller or equal than the second
new_value = arr[index]
arr[index] = arr[index + 1]
arr[index + 1] = new_value
end
end
keep_going = false if flagged == false
end
end
results = arr
end
# Find the maximum
def maximum(arr)
sort(arr).last
end
def minimum(arr)
sort(arr).first
end
# expect it to return 42 below
result = maximum([2, 42, 22, 02])
puts "max of 2, 42, 22, 02 is: #{result}"
# expect it to return 2 below
result = minimum([2, 42, 22, 02])
puts "min of 2, 42, 22, 02 is: #{result}"
# expect it to return nil when empty array is passed in
result = maximum([])
puts "max on empty set is: #{result.inspect}"
result = minimum([])
puts "min on empty set is: #{result.inspect}"
result = maximum([-23, 0, -3])
puts "max of -23, 0, -3 is: #{result}"
result = maximum([6])
puts "max of just 6 is: #{result}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment