code for chapter 4 in ruby
This commit is contained in:
10
04_quicksort/ruby/01_loop_sum.rb
Normal file
10
04_quicksort/ruby/01_loop_sum.rb
Normal file
@@ -0,0 +1,10 @@
|
||||
def sum(arr)
|
||||
total = 0
|
||||
arr.each do |x|
|
||||
total += x
|
||||
end
|
||||
|
||||
total
|
||||
end
|
||||
|
||||
puts sum([1, 2, 3, 4])
|
||||
4
04_quicksort/ruby/02_recursive_sum.rb
Normal file
4
04_quicksort/ruby/02_recursive_sum.rb
Normal file
@@ -0,0 +1,4 @@
|
||||
def sum(list)
|
||||
return 0 if list.empty?
|
||||
list[0] + sum(list[1..-1])
|
||||
end
|
||||
4
04_quicksort/ruby/03_recursive_count.rb
Normal file
4
04_quicksort/ruby/03_recursive_count.rb
Normal file
@@ -0,0 +1,4 @@
|
||||
def count(list)
|
||||
return 0 if list.empty?
|
||||
1 + count(list[1..-1])
|
||||
end
|
||||
9
04_quicksort/ruby/04_recursive_max.rb
Normal file
9
04_quicksort/ruby/04_recursive_max.rb
Normal file
@@ -0,0 +1,9 @@
|
||||
def max(list)
|
||||
if list.length == 2
|
||||
# condition ? then : else
|
||||
list[0] > list[1] ? list[0] : list[1]
|
||||
else
|
||||
sub_max = max(list[1..-1])
|
||||
list[0] > sub_max ? list[0] : sub_max
|
||||
end
|
||||
end
|
||||
18
04_quicksort/ruby/05_quicksort.rb
Normal file
18
04_quicksort/ruby/05_quicksort.rb
Normal file
@@ -0,0 +1,18 @@
|
||||
def quicksort(array)
|
||||
if array.length < 2
|
||||
# base case, arrays with 0 or 1 element are already "sorted"
|
||||
array
|
||||
else
|
||||
# recursive case
|
||||
pivot = array[0]
|
||||
# sub-array of all the elements less than the pivot
|
||||
rest = array[1..-1]
|
||||
less = rest.select { |i| i <= pivot }
|
||||
# sub-array of all the elements greater than the pivot
|
||||
greater = rest.select { |i| i > pivot }
|
||||
|
||||
quicksort(less) + [pivot] + quicksort(greater)
|
||||
end
|
||||
end
|
||||
|
||||
print quicksort([10, 5, 2, 3])
|
||||
Reference in New Issue
Block a user