mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-12-26 21:58:56 +01:00
Add bubble sort solution
This commit is contained in:
parent
55e5b2a90f
commit
772be7084b
1 changed files with 32 additions and 0 deletions
|
@ -13,4 +13,36 @@
|
|||
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]))
|
Loading…
Reference in a new issue