-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rb
More file actions
46 lines (39 loc) · 831 Bytes
/
main.rb
File metadata and controls
46 lines (39 loc) · 831 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
# frozen_string_literal: true
def verify_input(array)
if !array.is_a?(Array)
false
else
array.respond_to?('each') ? true : false
end
end
def bubble_sort(arr)
return unless verify_input(arr)
length = arr.length
loop do
sorted = true
(length - 1).times do |i|
next if i + 1 == arr.length
if arr[i] > arr[i + 1]
arr[i], arr[i + 1] = arr[i + 1], arr[i]
sorted = false
end
end
break if sorted
end
arr
end
def bubble_sort_by(arr)
return unless verify_input(arr)
raise 'Please provide a block' unless block_given?
loop do
swapped = true
(arr.length - 1).times do |i|
if yield(arr[i], arr[i + 1]).positive?
arr[i], arr[i + 1] = arr[i + 1], arr[i]
swapped = false
end
end
break unless swapped
end
arr
end