Commit 2a1426c

mo khan <mo@mokhan.ca>
2013-07-11 03:25:18
add notes and benchmark for quick sort
1 parent 00b8c6a
Changed files (2)
lib/quick_sort.rb
@@ -1,6 +1,5 @@
 class QuickSort
   def sort(items)
-    p items
     return items if items.size <= 1
 
     pivot = items[rand(items.size)]
spec/quick_sort_spec.rb
@@ -1,5 +1,14 @@
 require "spec_helper"
 
+# average case: O(n logn)
+# worst case: O(n^2)
+# Quick sort is a divide and conquer algorithm.
+# Base case: 0,1 elements in the array
+# First divide the list into two smaller lists (high list, and low list)
+# 1. pick a pivot value.
+# 2. move items smaller than pivot into smaller list, and greater into greater list.
+# 3. recursively split up lists until the base case
+# 4. combine the lesser list with the greater list
 describe QuickSort do
   let(:sut) { QuickSort.new }
 
@@ -14,6 +23,9 @@ describe QuickSort do
   it "should sort an array of numbers" do
     n = 600
     numbers = Array.new(n) { rand(n) }
-    sut.sort(numbers).should == numbers.sort
+    sorted_numbers = numbers.sort
+    Benchmark.bmbm do |x|
+      x.report("quick sort") { sut.sort(numbers).should == sorted_numbers }
+    end
   end
 end