Skip to content

Instantly share code, notes, and snippets.

@noqcks
Created September 3, 2014 22:59
Show Gist options
  • Save noqcks/a832a08214f71186ee54 to your computer and use it in GitHub Desktop.
Save noqcks/a832a08214f71186ee54 to your computer and use it in GitHub Desktop.
def BubbleSort(to_sort)
n = to_sort.length
sorted = false
until sorted
sorted = true
for i in 0..(n - 2)
if to_sort[i] > to_sort[i + 1]
sorted = false
to_sort[i], to_sort[i + 1] = to_sort[i + 1], to_sort[i]
end
end
end
return to_sort
end
def merge_sort(to_sort)
return to_sort if to_sort.count <= 1
middle = (to_sort.count / 2).to_i
left = to_sort[0..middle-1]
right = to_sort[middle..to_sort.length-1]
final = combine(merge_sort(left), merge_sort(right))
end
def combine(left,right)
return right.empty? ? left : right if left.empty? || right.empty?
smallest = left.first <= right.first ? left.shift : right.shift
combine(left, right).unshift(smallest)
end
def combine
if left.empty? || right.empty?
return right
elsif
# Find the maximum
def maximum(arr)
BubbleSort(arr).last
end
def minimum(arr)
BubbleSort(arr).first
end
# expect it to return 42 below
result = maximum([2, 42, 22, 02])
puts "max of 2, 42, 22, 02 is: #{result}"
# expect it to return 2 below
result = minimum([2, 42, 22, 02])
puts "min of 2, 42, 22, 02 is: #{result}"
# expect it to return nil when empty array is passed in
result = maximum([])
puts "max on empty set is: #{result.inspect}"
result = minimum([])
puts "min on empty set is: #{result.inspect}"
result = maximum([-23, 0, -3])
puts "max of -23, 0, -3 is: #{result}"
result = maximum([6])
puts "max of just 6 is: #{result}"
require 'benchmark'
arr = (1..10000).map { rand }
Benchmark.bm do |x|
x.report ("sort") {arr.sort}
x.report ("bubblesort") { BubbleSort(arr) }
x.report ("mergesort") { merge_sort(arr) }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment