Skip to content

Instantly share code, notes, and snippets.

@JessicaG
Last active August 29, 2015 14:04
Show Gist options
  • Save JessicaG/fdc45fde02170a2b290e to your computer and use it in GitHub Desktop.
Save JessicaG/fdc45fde02170a2b290e to your computer and use it in GitHub Desktop.
#Chad Brading && Jessica Goulding
# Design and implement an algorithm for merging sets of pre-sorted numbers into a single sorted set
# Beginner: Merge two sets
# Intermediate: Merge three sets
# Advanced: Merge n sets based on the data supplied
class MorningLogic
#Intermediate
def sort(d)
d.each do |n|
(d.size-1).times do |k|
if d[k] > d[k+1]
m = d[k+1]
d[k+1] = d[k]
d[k] = m
end
end
end
end
#Advanced
def merge(*args)
x = args.reduce([]) do |sum, n|
sum + n
end
sort(x)
end
end
a = [1,4,9]
b = [2,3,5]
c = [6,7,8]
l = [20, 5, 9, 50, 14, 37, 6]
example = MorningLogic.new
sorted = example.merge(a, b, c, l)
puts sorted
###In attempt to remove loop within a loop
class MorningLogic
def initialize(*args)
@array = merge(args)
end
def merge(a)
x = a.reduce([]) do |sum, n|
sum + n
end
end
def sort
@array.each do |n|
switch
end
end
def switch
(@array.size-1).times do |k|
if @array[k] > @array[k+1]
m = @array[k+1]
@array[k+1] = @array[k]
@array[k] = m
end
end
end
end
a = [1,4,9]
b = [2,3,5]
c = [6,7,8]
l = [20, 5, 9, 50, 14, 37, 6]
example = MorningLogic.new(a, b, c, l)
sorted = example.sort
puts sorted
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment