Skip to content

Commit c112bac

Browse files
committed
Implement Quick Sort in Ruby
1 parent 3866488 commit c112bac

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

quick_sort/QuickSort.rb

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
require 'time'
2+
3+
class QuickSort
4+
def quick_sort(arr, left, right)
5+
return if left >= right
6+
7+
pivot = arr[(left + right) / 2]
8+
l = left
9+
r = right
10+
11+
while l <= r
12+
l += 1 while arr[l] < pivot
13+
r -= 1 while arr[r] > pivot
14+
15+
if l <= r
16+
arr[l], arr[r] = arr[r], arr[l]
17+
l += 1
18+
r -= 1
19+
end
20+
end
21+
22+
quick_sort(arr, left, r)
23+
quick_sort(arr, l, right)
24+
25+
return arr
26+
end
27+
28+
arr = [17,72,27,77,43,100,6,9,92,37,1,50,36,67,45,98,33,54,19,91,99,65,3,69,12,79,18,42,90,16,84,51,70,29,61,2,14,76,39,95,81,97,82,96,63,58,53,89,11,5,20,47,23,88,44,62,83,7,34,74,10,57,64,22,32,48,4,46,80,13,71,38,25,93,15,21,73,30,66,26,56,55,8,24,52,94,49,40,87,60,31,75,41,59,28,78,35,86,68,85]
29+
30+
left = 0
31+
right = arr.size - 1;
32+
33+
start_time = Time.now
34+
35+
puts "=== Exec Quick Sort in Ruby ==="
36+
37+
result = QuickSort.new.quick_sort(arr, left, right)
38+
39+
puts result.to_s
40+
41+
end_time = Time.now
42+
43+
puts "Exec time: #{(end_time - start_time) * 100000} ms"
44+
end

0 commit comments

Comments
 (0)