Skip to content

Instantly share code, notes, and snippets.

@kaiguogit
Last active July 20, 2016 18:28
Show Gist options
  • Save kaiguogit/14b353caed06af88842c0c499b14aaa9 to your computer and use it in GitHub Desktop.
Save kaiguogit/14b353caed06af88842c0c499b14aaa9 to your computer and use it in GitHub Desktop.
Merge_sort
def merge_sort(arr)
return arr if arr.length <=1
left = []
right = []
arr.each_index do |index|
index.odd? ? left.push(arr[index]) : right.push(arr[index])
end
left = merge_sort(left)
right = merge_sort(right)
merge(left,right)
end
def merge(left, right)
result = []
while left.length != 0 && right.length != 0
left[0] < right[0] ? result.push(left.slice!(0)) : result.push(right.slice!(0))
end
return result + left if left.length != 0
return result + right if right.length != 0
end
def random_array_generator(length,startnumber,endnumber)
prng = Random.new
result = []
length.times do
result.push(prng.rand(startnumber..endnumber))
end
result
end
array = random_array_generator(20,0,100)
puts "Random array is #{array}"
puts "Sorted array is #{merge_sort(array)}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment