Last active
August 29, 2015 13:56
-
-
Save ewhitebloom/9175249 to your computer and use it in GitHub Desktop.
Sorting and Averaging Algorithms
This file contains 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
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}" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
good job!
.rb
so we can get the benefit of GitHub's Ruby Syntax highlighting