Last active
August 29, 2015 14:25
-
-
Save Yorgg/2997fd90dca3b493dcdd to your computer and use it in GitHub Desktop.
Sorting in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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