Skip to content

Instantly share code, notes, and snippets.

@tdlm
Created December 2, 2016 05:22
Show Gist options
  • Save tdlm/d1d83bab31b57fd968764ebb73b033dd to your computer and use it in GitHub Desktop.
Save tdlm/d1d83bab31b57fd968764ebb73b033dd to your computer and use it in GitHub Desktop.
#!/bin/ruby
class BubbleSort
def initialize(unsorted_array)
@array = unsorted_array
@swaps = 0
end
def sort
@array.each_with_index do |val, key|
for i in [email protected] do
if @array[i] > @array[i+1]
@array[i], @array[i+1] = @array[i+1], @array[i]
@swaps += 1
end
end
end
@array
end
def get_swaps
@swaps
end
end
b_sort = BubbleSort.new([3,5,2,1])
sorted_array = b_sort.sort
printf("Array is sorted in %d swaps.\n", b_sort.get_swaps)
printf("First Element: %d\n", sorted_array.first)
printf("Last Element: %d\n", sorted_array.last)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment