Skip to content

Commit 489aeec

Browse files
committed
Adding in chapter 6 select
With some help from chatGPT, added in the r_select algorithms that was discussed on chapter 6, algorithms illuminated part 1.
1 parent fe8462e commit 489aeec

2 files changed

Lines changed: 53 additions & 0 deletions

File tree

README.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,4 +42,18 @@ recursive 0.059381 0.001229 0.060610 ( 0.060931)
4242
>avg: 4.702769 0.064204 4.766973 ( 4.793619)
4343
...End of Benchmark.
4444
```
45+
### Select Algorithm
4546

47+
#### RSelect Algorithm
48+
49+
50+
The find_order_smallest method first checks if the array is empty or if k is greater than the length of the array. If either of these conditions is true, it returns nil.
51+
The method then selects a random pivot element from the array using the sample method. It then partitions the array into three parts: elements less than the pivot, elements equal to the pivot, and elements greater than the pivot.
52+
It then uses recursion to continue the Select algorithm on the appropriate partition of the array depending on the value of k. If k is less than or equal to the length of the less partition, the method is called recursively on the less partition with the same value of k. If k is less than or equal to the length of the less and equal partitions combined, the method returns the pivot value. Otherwise, the method is called recursively on the greater partition with the value of k adjusted to account for the elements in the less and equal partitions.
53+
54+
irb -r ./r_select.rb
55+
56+
```
57+
> RSelect.find_order_smallest([4,3,2,5,7,9], 3)
58+
> 4
59+
```

lib/r_select.rb

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#
2+
# Ruby RSelect example
3+
# RSelect.find_order_smallest([3,6,7,8,9,4,5], 2)
4+
# 4
5+
class RSelect
6+
#
7+
# Takes an array and a value k as input.
8+
# Returns the kth smallest element in the array using the Select algorithm.
9+
#
10+
# ex. if you want to smallest number in the array, k =1 (i.e. 1st smallest),
11+
# then if you want 2nd, 3rd, 4th,... use k= 2 or 3 or 4...
12+
#
13+
def self.find_order_smallest(array, k)
14+
return nil if array.empty? || k > array.length
15+
16+
pivot = array.sample
17+
less = []
18+
equal = []
19+
greater = []
20+
21+
array.each do |element|
22+
if element < pivot
23+
less << element
24+
elsif element == pivot
25+
equal << element
26+
else
27+
greater << element
28+
end
29+
end
30+
31+
if k <= less.length
32+
find_order_smallest(less, k)
33+
elsif k <= less.length + equal.length
34+
pivot
35+
else
36+
find_order_smallest(greater, k - less.length - equal.length)
37+
end
38+
end
39+
end

0 commit comments

Comments
 (0)