Skip to content

Instantly share code, notes, and snippets.

@dekaikiwi
Created December 16, 2018 15:52
Show Gist options
  • Save dekaikiwi/ee02e1f9bc5f44599a38bee509780ca3 to your computer and use it in GitHub Desktop.
Save dekaikiwi/ee02e1f9bc5f44599a38bee509780ca3 to your computer and use it in GitHub Desktop.
Quick attempt at Bubble Sort implementation in Ruby (needs to be improved)
def bubble_sort(arr, swap_count = 0)
time_start = Time.now
total_swap_count = 0
swap_count = nil
while swap_count.nil? || swap_count > 0
swap_count = 0
arr.each_with_index do |i, index|
pos = index
next_item = arr[pos+1]
item = i
while !next_item.nil? && item > next_item do
if item > next_item
arr[pos], arr[pos+1] = next_item, item
swap_count += 1
end
pos += 1
item = arr[pos]
next_item = arr[pos+1]
end
end
total_swap_count += swap_count
end
puts "Sorted in #{total_swap_count} swaps"
puts "Sorted in #{Time.now - time_start} seconds"
return arr
end
bubble_sort([*0..10000].shuffle)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment