Commit 00b8c6a
Changed files (3)
lib/quick_sort.rb
@@ -0,0 +1,19 @@
+class QuickSort
+ def sort(items)
+ p items
+ return items if items.size <= 1
+
+ pivot = items[rand(items.size)]
+ less, pivots, greater = [], [], []
+ items.each do |x|
+ if x < pivot
+ less << x
+ elsif x > pivot
+ greater << x
+ else
+ pivots << x
+ end
+ end
+ sort(less) + pivots + sort(greater)
+ end
+end
spec/quick_sort_spec.rb
@@ -0,0 +1,19 @@
+require "spec_helper"
+
+describe QuickSort do
+ let(:sut) { QuickSort.new }
+
+ it "should sort an empty array" do
+ sut.sort([]).should == []
+ end
+
+ it "should sort an array with one item" do
+ sut.sort([1]).should == [1]
+ end
+
+ it "should sort an array of numbers" do
+ n = 600
+ numbers = Array.new(n) { rand(n) }
+ sut.sort(numbers).should == numbers.sort
+ end
+end
spec/spec_helper.rb
@@ -1,3 +1,4 @@
require 'benchmark'
require_relative '../lib/bubble_sort'
require_relative '../lib/insertion_sort'
+require_relative '../lib/quick_sort'