mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-12-27 21:58:57 +01:00
Add bubble sort solution
This commit is contained in:
parent
55e5b2a90f
commit
772be7084b
1 changed files with 32 additions and 0 deletions
|
@ -14,3 +14,35 @@ def sorted_squares(nums)
|
||||||
nums.map! { |num| num**2 }.sort
|
nums.map! { |num| num**2 }.sort
|
||||||
end
|
end
|
||||||
print(sorted_squares([4, -1, -9, 2]))
|
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]))
|
Loading…
Reference in a new issue