Skip to content

Instantly share code, notes, and snippets.

@Yorgg

Yorgg/sort-ruby.rb

Last active Aug 29, 2015
Embed
What would you like to do?
Sorting in Ruby
#My implementation of sorting algorithms in Ruby
#insertion sort
def sort_insert(a)
index = 1
while index < a.length
value = a[index]
a[0...index].each_with_index do |sorted_value, i|
if value < sorted_value
a.slice!(index)
a.insert(i, value)
break
end
end
index += 1
end
a
end
#selection sort
def sort(a)
n = a.size - 1
n.times do |i|
index = i
(i + 1).upto(n) { |j| index = j if a[j] < a[index] }
a[i], a[index] = a[index], a[i] unless index == i
end
a
end
#merge sort
def mergesort(list)
return list if list.size == 1
length = list.length/2 - 1
left = mergesort(list[0..length])
right = mergesort(list[length+1..-1])
merge(left,right)
end
def merge(left,right)
lindex = rindex = 0
out = []
loop do
if left[lindex] == nil
out += right[rindex..-1]
break
elsif right[rindex] == nil
out += left[lindex..-1]
break
end
if right[rindex] < left[lindex]
out << right[rindex]
rindex += 1
else
out << left[lindex]
lindex += 1
end
end
out
end
#bubble sort
def bubble_sort(a)
length = a.size - 1
loop do
switch = false
1.upto(length) do |i|
if a[i] < a[i-1]
a[i], a[i-1] = a[i-1], a[i]
switch = true
end
end
return a unless switch
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment