Skip to content

Instantly share code, notes, and snippets.

@luizbafilho
Last active August 29, 2015 14:22
Show Gist options
  • Save luizbafilho/29b423a8b03ba8dd66e0 to your computer and use it in GitHub Desktop.
Save luizbafilho/29b423a8b03ba8dd66e0 to your computer and use it in GitHub Desktop.
require 'rspec'
class Stats
def self.mean(array)
array.inject(:+) / array.size.to_f
end
def self.median(array)
mid = array.length / 2
sorted = array.sort
array.length.odd? ? sorted[mid] : (sorted[mid] + sorted[mid - 1]) / 2.0
end
end
class Sorter
def self.quick_sort!(elems)
sort(elems, 0, elems.length - 1)
end
private
def self.partition(elems, left, right)
x = elems[right]
i = left - 1
for j in left..right - 1
if elems[j] <= x
i += 1
elems[i], elems[j] = elems[j], elems[i]
end
end
elems[i + 1], elems[right] = elems[right], elems[i + 1]
i + 1
end
def self.sort(elems, left, right)
if left < right
pivot = partition(elems, left, right)
sort(elems, left, pivot - 1)
sort(elems, pivot + 1, right)
end
elems
end
end
RSpec.describe 'Test' do
let(:array) { [5, 3, 2, 1, 4] }
describe Sorter do
describe '#quick_sort!' do
it 'sorts using quick sort algorithm' do
expect(Sorter.quick_sort!(array)).to eq [1, 2, 3, 4, 5]
end
end
end
describe Stats do
describe '#mean' do
it 'returns the mean' do
expect(Stats.mean(array)).to eq(3.0)
end
end
describe '#median' do
it 'returns the median' do
expect(Stats.median(array)).to eq(3.0)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment