Commit fccb329

mo khan <mo@mokhan.ca>
2013-07-11 02:58:48
implement insertion sort
1 parent c1b39b4
lib/insertion_sort.rb
@@ -1,5 +1,14 @@
 class InsertionSort
   def sort(items)
+    items.size.times do |n|
+      j = n
+      while j >= 0 do
+        if (items[j] <=> items[j+1]) == 1
+          items[j], items[j+1] = items[j+1], items[j]
+        end
+        j-=1
+      end
+    end
     items
   end
 end
spec/insertion_sort_spec.rb
@@ -1,12 +1,22 @@
 require "spec_helper"
 
 describe InsertionSort do
+  let(:sut) { InsertionSort.new }
+
   it "should sort an empty array" do
-    InsertionSort.new.sort([]).should == []
+    sut.sort([]).should == []
   end
 
   it "should sort an array with one item" do
-    InsertionSort.new.sort([1]).should == [1]
+    sut.sort([1]).should == [1]
+  end
+
+  it "should sort an array of numbers" do
+    n = 200
+    numbers = Array.new(n) { rand(n) }
+    Benchmark.bmbm do |x|
+      x.report("insertion sort") { sut.sort(numbers).should == numbers.sort }
+    end
   end
 end