selection sort


See On Github

Data

Contributor

Generic placeholder thumbnail

by majjoha

in ruby

Source Code

# This implementation is loosely based on Sedwick and Waynes selection sort from
# fourth edition of the quite amazing "Algorithms" text book. It is rewritten
# from Java to Ruby.

def selection_sort(array)
  array.each_with_index do |item, i|
    min = i
    i.upto(array.length-1) do |j|
      min = j if array[j] < array[min]
    end
    array[i], array[min] = array[min], array[i]
  end
  array
end
require 'rspec'
require './selection_sort'

describe '#selection_sort' do
  context 'Not sorted' do
    before(:each) { @array = ['S','O','R','T','E','X','A','M','P','L','E'] }

    it 'orders the array' do
      sorted_array = selection_sort(@array)
      expect(sorted_array).to eq @array.sort
    end
  end

  context 'Empty array' do
    before(:each) { @array = [] }

    it 'returns an empty array' do
      sorted_array = selection_sort(@array)
      expect(sorted_array).to eq []
    end
  end
end