Last active
August 5, 2020 05:48
-
-
Save netsprout/370b381351ef2e769cb70908ea62314e to your computer and use it in GitHub Desktop.
My bubble sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/ruby | |
require 'json' | |
require 'stringio' | |
def count_swaps(sort_me) | |
is_sorted = false | |
swap_count = 0 | |
while is_sorted == false | |
is_sorted = true | |
current_point = 0 | |
end_point = sort_me.length - 1 | |
while current_point < end_point do | |
if sort_me[current_point] > sort_me[current_point + 1] | |
is_sorted = false | |
swap_count += 1 | |
swap(sort_me, current_point, current_point + 1) | |
end | |
current_point += 1 | |
end | |
end_point = end_point - 1 | |
end | |
puts "Array is sorted in #{swap_count} swaps." | |
puts "First Element: #{sort_me[0]}" | |
puts "Last Element: #{sort_me[-1]}" | |
end | |
def swap(sort_list, first, second) | |
value_first = sort_list[second] | |
value_second = sort_list[first] | |
sort_list[first] = value_first | |
sort_list[second] = value_second | |
end | |
n = gets.to_i | |
a = gets.rstrip.split(' ').map(&:to_i) | |
count_swaps a |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment