Skip to content

Instantly share code, notes, and snippets.

@ewhitebloom
Last active August 29, 2015 13:56
Show Gist options
  • Save ewhitebloom/9175249 to your computer and use it in GitHub Desktop.
Save ewhitebloom/9175249 to your computer and use it in GitHub Desktop.
Sorting and Averaging Algorithms
nums = [75, 100, 85, 65, 84, 87, 95]
def average(nums)
sum = 0
nums.each do |number|
sum += number
end
sum/nums.length
end
def sort(unsorted)
sorted = []
sorted << unsorted.last
unsorted.pop
until unsorted[0] == nil
sorted.each do |sorted_num|
break if unsorted.last == nil
if unsorted.last.to_i < sorted_num.to_i
index = sorted.index(sorted_num)
sorted.insert(index, unsorted.last)
unsorted.pop
break
elsif unsorted.last.to_i > sorted.last
sorted.push(unsorted.last)
unsorted.pop
break
end
end
end
sorted
end
puts "Average: #{average(nums)}"
sorted = sort(nums)
puts "Sorted array: #{sorted}"
puts "Max: #{sorted.last}"
puts "Min: #{sorted.first}"
@dpickett
Copy link

good job!

  • Do you have to sort the list for you to retrieve the min and max values?
  • I like that you used a method for the average with an appropriate return value.
  • Can you refactor your solution so that it loops through the Array only once? This would perform better.
  • Also be sure to save the file in the gist as a .rb so we can get the benefit of GitHub's Ruby Syntax highlighting

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment