Title / Description
Code #!/usr/bin/ruby def generate_shuffled_sequence so_many = 100 so_many.times.map { |i| i+1 }.shuffle end def generate_random_array so_many = 100 so_many.times.map { |i| rand(so_many) }.shuffle end def sort_swap_neighbors shuffled_array = [] # Sorts by comparing neighbors is_sorted = false until is_sorted do is_sorted = true for i in 0..(shuffled_array.length-2) do if shuffled_array[i] > shuffled_array[i+1] shuffled_array[i], shuffled_array[i+1] = shuffled_array[i+1], shuffled_array[i] is_sorted = false end end end shuffled_array end def sort_natural shuffled_array = [] # Sorts by repeatedly finding the lowest value in the unsorted array, # and moving it out to the sorted array. sorted_array = [] until shuffled_array.empty? do lowest_element_pos = 0 for i in 0..(shuffled_array.length-1) do lowest_element_pos = i if shuffled_array[lowest_element_pos] > shuffled_array[i] end sorted_array.push shuffled_array.delete_at(lowest_element_pos) end sorted_array end def sort_by_fill shuffled_array = [] # Sorts by moving each value from the unsorted array, into the right order # inside the sorted one. sorted_array = [shuffled_array.delete_at(0), shuffled_array.delete_at(0)] sorted_array.reverse! if sorted_array[0] > sorted_array[1] until shuffled_array.empty? do current_value = shuffled_array.shift if current_value <= sorted_array.first sorted_array.unshift current_value elsif current_value >= sorted_array.last sorted_array.push current_value else for i in 0..(sorted_array.length-1) do if current_value > sorted_array[i] and current_value < sorted_array[i+1] sorted_array.insert(i+1, current_value) end end end end sorted_array end def sort_brute_force shuffled_array = [] # This algorithm accomplishes sorting by brute force. Finds the lowest and # highest values, and then itteratively asserts it's presence. sorted_array = [] min, max = 0, 0 for i in 0..(shuffled_array.length-1) min = shuffled_array[i] if shuffled_array[i] < min max = shuffled_array[i] if shuffled_array[i] > max end until shuffled_array.empty? do for value in min..max do for i in 0..(shuffled_array.length-1) do sorted_array.push shuffled_array.delete_at i if shuffled_array[i] == value end end end sorted_array end # Shuffled sequences, default length is 100 p sort_swap_neighbors generate_shuffled_sequence p sort_natural generate_shuffled_sequence p sort_by_fill generate_shuffled_sequence p sort_brute_force generate_shuffled_sequence # Random arrays, default length is 100 p sort_swap_neighbors generate_random_array p sort_natural generate_random_array p sort_by_fill generate_random_array p sort_brute_force generate_random_array
Author
Highlight as C C++ CSS Clojure Delphi ERb Groovy (beta) HAML HTML JSON Java JavaScript PHP Plain text Python Ruby SQL XML YAML diff code