Skip to content

Instantly share code, notes, and snippets.

@sirmxanot
Created October 26, 2012 00:31
Show Gist options
  • Save sirmxanot/3956326 to your computer and use it in GitHub Desktop.
Save sirmxanot/3956326 to your computer and use it in GitHub Desktop.
weird error
ArgumentError: comparison of Fixnum with nil failed
from mergesort3.rb:34:in `<'
from mergesort3.rb:34:in `block in merge'
from mergesort3.rb:31:in `each'
from mergesort3.rb:31:in `merge'
from mergesort3.rb:17:in `merge_sort'
from mergesort3.rb:14:in `merge_sort'
from (irb):4
from /usr/bin/irb:12:in `<main>'
def merge_sort(m)
#base case
if m.length <= 1
m
#all other cases
else
#intialize variables
left = Array.new
right = Array.new
middle = m.length/2
#split first half to left and second half to right, call merge sort recursively
left = merge_sort(m[0..middle-1])
right = merge_sort(m[middle..-1])
#merge left and right
merge = merge(left, right)
#return merge
merge
end
end
def merge(left, right)
#initializations
output = Array.new(left.length+right.length)
i = 0
j = 0
#go through each element in the ouput array and insert a value from left or right
output.each do |k|
#before the counters for either left and right have ended
if i < left.length && j < right.length
if left[i] < right[j]
k=left[i]
i += 1
else
k=right[j]
j += 1
end
#when counter for left has reached end, but right has not
elsif i >= left.length && j < right.length
k=right[j]
j += 1
#when counter for right has reached end, but left has not
elsif i < left.length && j >= right.length
k=left[i]
i += 1
end
end
#return ouput
output
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment