Skip to content
This repository was archived by the owner on Dec 12, 2023. It is now read-only.

Commit 69376b6

Browse files
committed
Merge pull request #81 from T145/master
More ruby algorithms
2 parents 1fa06e3 + b3f9c7c commit 69376b6

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

merge-sort/merge-sort.rb

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
def merge_sort(a)
2+
return a if a.size <= 1
3+
l, r = split_array(a)
4+
combine(merge_sort(l), merge_sort(r))
5+
end
6+
7+
def split_array(a)
8+
mid = (a.size / 2).round
9+
[a.take(mid), a.drop(mid)]
10+
end
11+
12+
def combine(a, b)
13+
return b.empty? ? a : b if a.empty? || b.empty?
14+
smallest = a.first <= b.first ? a.shift : b.shift
15+
combine(a, b).unshift(smallest)
16+
end
17+
18+
# a = [6, 23, 53, 1, 2, 5, 62, 61, 33, 21, 14, 6, 23].shuffle
19+
# p merge_sort(a)

quick-sort/quick-sort.rb

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# NOTE: Ruby has a built in sorting method, `sort!`, that actually uses a quick-sort process; this just demonstrates an implementation.
2+
3+
def quick_sort(array) # quick sort algorithm
4+
array.quick_sort!
5+
end
6+
7+
def self.quick_sort!(array)
8+
process(array, 0, array.size - 1)
9+
end
10+
11+
private
12+
13+
def self.process(array, left, right)
14+
if left < right
15+
pivot = partition(array, left, right)
16+
process(array, left, pivot - 1)
17+
process(array, pivot + 1, right)
18+
end
19+
array
20+
end
21+
22+
def self.partition(array, left, right)
23+
x = array[right]
24+
i = left - 1
25+
(left..right - 1).each do |j|
26+
if array[j] <= x
27+
i += 1
28+
array[i], array[j] = array[j], array[i]
29+
end
30+
end
31+
array[i + 1], array[right] = array[right], array[i + 1]
32+
i + 1
33+
end

0 commit comments

Comments
 (0)