-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathsorted_array.rb
More file actions
53 lines (44 loc) · 819 Bytes
/
sorted_array.rb
File metadata and controls
53 lines (44 loc) · 819 Bytes
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
class Array
def add(item)
if item.class == Array
item.each { |x| add x }
else
res = seek { |x| x <=> item }
insert(~res, item) if res < 0
end
self
end
def del(item)
if item.class == Array
item.each { |x| del x }
else
res = seek { |x| x <=> item }
delete_at(res) if res >= 0
end
self
end
def seek
return nil unless block_given?
lo, hi = 0, self.length - 1
while lo <= hi do
mid = lo + (hi - lo) / 2
val = self[mid]
res = yield(val)
if res == -1
lo = mid + 1
elsif res == 1
hi = mid - 1
else
return mid
end
end
return ~lo
end
end
if __FILE__ == $PROGRAM_NAME
a = []
a.add(10).add(5).add([2, 3])
p a
a.del(5).del(2).del([3, 10])
p a
end