-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathbubble.rb
49 lines (45 loc) · 1.1 KB
/
bubble.rb
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
# coding: utf-8
# Bubble sort: A very naive sort that keeps swapping elements until the container
# is sorted. Requirements: Needs to be able to compare elements with <=>, and
# the [] []= methods should be implemented for the container. Time Complexity:
# О(n^2). Space Complexity: О(n) total, O(1) auxiliary. Stable: Yes.
#
# [5, 4, 3, 1, 2].bubble_sort! => [1, 2, 3, 4, 5]
class Array
def swap(first, second)
self[first], self[second] = self[second], self[first]
self
end
def bubble_sort!
loop do
swapped = false
(self.size - 1).times do |index|
if self[index] > self[index + 1]
swap index, index + 1
swapped = true
end
end
break unless swapped
end
self
end
# def bubble_sort!
# length.times do |j|
# for i in 1...(length - j)
# swap i - 1, i if self[i - 1] < self[i]
# end
# end
#
# self
# end
#
# def bubble_sort!
# each_index do |index|
# (length - 1).downto( index ) do |i|
# swap i - 1, i if self[i - 1] < self[i]
# end
# end
#
# self
# end
end