Skip to content

Instantly share code, notes, and snippets.

@reddavis
Created April 11, 2009 10:49
Show Gist options
  • Save reddavis/93525 to your computer and use it in GitHub Desktop.
Save reddavis/93525 to your computer and use it in GitHub Desktop.
# Insertion Sorting Algorithm for array of number
def sorter(*args)
args.each_with_index do |number, index|
b = index - 1
while b >= 0
break if args[b] <= number
args[b + 1] = args[b]
b -= 1
end
args[b + 1] = number
end
end
puts sorter(5, 3, 0, 7, 2, 8)
# Insertion Sorting Algorithm for string
def string_sorter(string)
array = string.split('')
array.each_with_index do |letter, index|
b = index - 1
while b >= 0
break if array[b][0].to_s.to_i <= letter[0].to_s.to_i
array[b + 1] = array[b]
b -= 1
end
array[b + 1] = letter
end
array.to_s
end
puts string_sorter('dbcsaez')
# Divide and Conquer Algorithm for sorting Integers
def divide_and_conquer(a)
return a if a.size <= 1
middle = (a.size/2) # Set the half way mark
left = a[0...middle]
right = a[middle...a.size]
merge_it(divide_and_conquer(left), divide_and_conquer(right))
end
def merge_it(left, right)
sorted = []
until left.empty? || right.empty?
if left.first <= right.first
sorted << left.shift
else
sorted << right.shift
end
end
sorted + left + right
end
#divide_and_conquer([4,7,2,3,7,3,34,6,24,654,1,754,234,7,5,23,543,234,875676])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment