forked from kelvins/algorithms-and-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 1
/
quick_sort.rb
56 lines (48 loc) · 1.22 KB
/
quick_sort.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class Quicksort
attr_reader :array_sorted
def initialize
@array_sorted = []
end
def init(array)
quick_sort(array)
end
private
def quick_sort(array, compare = lambda { |a, b| a <=> b })
inner(array, 0, array.length - 1, compare)
end
def inner(array, left, right, compare)
if left < right
pivot = partition_random(array, left, right, compare)
inner(array, left, pivot - 1, compare)
inner(array, pivot + 1, right, compare)
end
@array_sorted = array
end
def partition_random(array, left, right, compare)
pivot = left + (rand * (right - left)).floor
if pivot != right
array[right], array[pivot] = array[pivot], array[right]
end
return partition_right(array, left, right, compare)
end
def partition_right(array, left, right, compare)
pivot = array[right]
mid = left
(mid..right - 1).each do |i|
if compare.call(array[i], pivot) <= 0
if i != mid
array[i], array[mid] = array[mid], array[i]
end
mid += 1
end
end
if right != mid
array[right], array[mid] = array[mid], array[right]
end
return mid
end
end
# test
q_s = Quicksort.new
q_s.init([1,4,10,2,3,32,0])
p q_s.array_sorted