Skip to content

Instantly share code, notes, and snippets.

@addie
Last active August 29, 2015 14:27
Show Gist options
  • Save addie/bb8ed842ade1cd7b69a9 to your computer and use it in GitHub Desktop.
Save addie/bb8ed842ade1cd7b69a9 to your computer and use it in GitHub Desktop.
Collection of Algorithms in Ruby
def insertion_sort(array)
array.each do |i|
value = array[i]
j = i - 1
while j >= 0 and array[j] > value
array[j+1] = array[j]
j -= 1
end
array[j+1] = value
end
array
end
def insertion_sort2(array)
array.each do |i|
value = delete_at i
j = i - 1
j -= 1 while j >= 0 && value < array[j]
insert(j + 1, value)
end
array
end
def bubble_sort(array)
n = array.length
loop do
swapped = false
(n-1).times do |i|
if array[i] > array[i+1]
array[i], array[i+1] = array[i+1], array[i]
swapped = true
end
end
break if not swapped
end
array
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment