Sort the elements of two sorted arrays without using .sort method and put the sorted elements in a new array in RUBY
I have two arrays, like this:
a = [1,4,6,9]
b = [2,5,7,8]
and my output should be:
c = [1,2,4,5,6,7,8,9]
How do I do this?
Sort the elements of two sorted arrays without using .sort method and put the sorted elements in a new array in RUBY
I have two arrays, like this:
a = [1,4,6,9]
b = [2,5,7,8]
and my output should be:
c = [1,2,4,5,6,7,8,9]
How do I do this?
Here is a function that will help you do what you want.
def my_sort_function(a,b)
n = a.length + b.length
if a.length < b.length
min = a.length
else
min = b.length
end
c=[]
min.times do |i|
if a[i] > b[i]
c << b[i]
c << a[i]
else
c << a[i]
c << b[i]
end
end
if min == a.length
(c << b[(min)..(b.length-1)]).flatten!
else
(c << a[(min)..(a.length-1)]).flatten!
end
loop do
swapped = false
(n-1).times do |i|
if c[i] > c[i+1]
c[i], c[i+1] = c[i+1], c[i]
swapped = true
end
end
break if not swapped
end
c
end
a = [1,4,6]
b = [2,5,7,8]
puts a #=> a:[1,4,6]
puts b #=> b:[2,5,7,8]
c= my_sort_function(a,b)
puts c #=> c:[1,2,4,5,6,7,8]
puts "sorting Done!"
You cerainly want to make use of the fact that the two arrays to be merged are already sorted. This is one way to do that:
def merge_sort(a,b)
ac, bc = a.dup, b.dup
(a.size+b.size).times.each_with_object([]) do |_,c|
c <<
case [ac.any?, bc.any?]
when [true,true] then (ac.first <= bc.first) ? ac.shift : bc.shift
when [true,false] then ac.shift
else bc.shift
end
end
end
a = [1,4,6,9]
b = [2,5,7,8]
c = merge_sort a,b
#=> [1,2,4,5,6,7,8,9]
The first line is to avoid mutating (changing) a or b.
a, b and c.