Sha256: eb7fd55073c861e2b23999a0a08c8bf884851d809fa30185989645ff575833ae

Contents?: true

Size: 1.45 KB

Versions: 1

Compression:

Stored size: 1.45 KB

Contents

require "group_d_2016_gem/version"

module GroupD2016Gem
  class Sorter
    def bubble_sort(a)
        n = a.size
        0.upto(n - 2) do |i|
            (n - 1).downto(i + 1) do |j|
                if a[j] < a[j - 1]
                    a[j], a[j - 1] = a[j - 1], a[j]
                    p a
                end
            end
        end
        a 
    end

    def quick_sort(a)
        if a.size <= 1
            return a
        end
        pivot = a.delete_at(a.size / 2)
        smaller, bigger = a.partition {|i| i < pivot}
        ret = quick_sort(smaller) + [pivot] + quick_sort(bigger)
        return ret  
    end
  
    # Merge Sort 
    # Use this method if you want to sort.
    def merge_sort(list)
      length = list.length

      if length <= 1
	return list
      end
      
      mid = length/2
      a = list.slice(0...mid)
      b = list.slice(mid..-1)
      ma = merge_sort(a)
      mb = merge_sort(b)

      merge(ma, mb)
    end

    # Merge the list
    def merge(a, b)
      res = []
      until a.empty? && b.empty?
	res <<
	  case
	  when a.empty? then b.shift
	  when b.empty? then a.shift
	  when a.first < b.first then a.shift
	  else b.shift
	  end
      end
      res
    end

    def select_sort(a)
      n= a.size
      0.upto(n - 2) do |i|
        min = i
        (i + 1).upto(n - 1) do |j|
           min = j if a[j] < a[min]
        end
        if i != min
          a[i], a[min] = a[min], a[i]
        end
       end
       a
    end
  end
end


Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
group_d_2016_gem-0.1.0 lib/group_d_2016_gem.rb