Add bubble sort solution

This commit is contained in:
Jessica Kwok 2021-03-10 14:27:21 -08:00
parent 55e5b2a90f
commit 772be7084b

View file

@ -14,3 +14,35 @@ def sorted_squares(nums)
nums.map! { |num| num**2 }.sort
end
print(sorted_squares([4, -1, -9, 2]))
#
# Approach 2: is using bubble sort
#
def bubble_sort(array)
array_length = array.size
return array if array_length <= 1
loop do
swapped = false
(array_length - 1).times do |i|
if array[i] > array[i + 1]
array[i], array[i + 1] = array[i + 1], array[i]
swapped = true
end
end
break unless swapped
end
array
end
#
# Time complexity analysis for Approach 1 & 2
#
def sorted_squares(nums)
# This takes O(n)
nums.map! { |num| num**2 }
# This can take Ο(n logn)
bubble_sort(nums)
end
print(sorted_squares([4, -1, -9, 2]))