Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

David Madden http://moose56.com

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Bubble Sort in Ruby

// description of your code here

def bubble_sort(list)
  return list if list.size <= 1 # already sorted

  loop do
    swapped = false
    0.upto(list.size-2) do |i|
      if list[i] > list[i+1]
        list[i], list[i+1] = list[i+1], list[i] # swap values
        swapped = true
      end
    end
    break unless swapped
  end

  list
end

Selection Sort in Ruby

Simple implimentation of a selection sort in ruby

def selection_sort(list)
  return list if list.size <= 1 # already sorted

  0.upto(list.length-2) do |i|
    min = i # smallest value
    (i+1).upto(list.length-1) { |j| min = j if list[j] < list[min] } # find new smallest
    list[i], list[min] = list[min], list[i] if i != min #swap values
  end

  list
end
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS