]> gitweb.factorcode.org Git - factor.git/commitdiff
sorting.quick: better interface, allow comparison to be passed in.
authorJohn Benediktsson <mrjbq7@gmail.com>
Tue, 10 Jun 2014 23:45:41 +0000 (16:45 -0700)
committerJohn Benediktsson <mrjbq7@gmail.com>
Tue, 10 Jun 2014 23:45:41 +0000 (16:45 -0700)
extra/sorting/quick/quick-tests.factor
extra/sorting/quick/quick.factor

index 1afb80c5a048feca3a4891456f6bdc139c3ecb0f..739f8d88f301cacff7025f61de22c0733949a79d 100644 (file)
@@ -1,6 +1,13 @@
-USING: kernel tools.test ;
+USING: kernel sequences tools.test ;
 IN: sorting.quick
 
-{ { } } [ { } dup quicksort ] unit-test
-{ { 1 } } [ { 1 } dup quicksort ] unit-test
-{ { 1 2 3 4 5 } } [ { 1 4 2 5 3 } dup quicksort ] unit-test
+{ { } } [ { } dup natural-sort! ] unit-test
+{ { 1 } } [ { 1 } dup natural-sort! ] unit-test
+{ { 1 2 3 4 5 } } [ { 1 4 2 5 3 } dup natural-sort! ] unit-test
+
+{
+    { "dino" "fred" "wilma" "betty" "barney" "pebbles" "bamm-bamm" }
+} [
+    { "fred" "wilma" "pebbles" "dino" "barney" "betty" "bamm-bamm" }
+    dup [ length ] sort-with!
+] unit-test
index e585cb190f976ed30bf1b52f4baebc89f766f4bf..38ee1b96273353e21e47834a52eed9377042c4d0 100644 (file)
@@ -8,25 +8,41 @@ IN: sorting.quick
 
 <PRIVATE
 
-:: (quicksort) ( seq from to -- )
+:: quicksort ( seq from to quot -- )
     from to < [
         from to + 2/ seq nth-unsafe :> pivot
 
         from to [ 2dup <= ] [
-            [ over seq nth-unsafe pivot before? ] [ [ 1 + ] dip ] while
-            [ dup  seq nth-unsafe pivot after? ] [ 1 - ] while
+            [
+                over seq nth-unsafe pivot quot call( x x -- x )
+                +lt+ eq?
+            ] [ [ 1 + ] dip ] while
+
+            [
+                dup seq nth-unsafe pivot quot call( x x -- x )
+                +gt+ eq?
+            ] [ 1 - ] while
+
             2dup <= [
                 [ seq exchange-unsafe ]
                 [ [ 1 + ] [ 1 - ] bi* ] 2bi
             ] when
         ] while
 
-        [ seq from ] dip (quicksort)
-        [ seq ] dip to (quicksort)
-
+        [ seq from ] dip quot quicksort
+        [ seq ] dip to quot quicksort
     ] when ; inline recursive
 
 PRIVATE>
 
-: quicksort ( seq -- )
-    0 over length 1 - (quicksort) ;
+: sort! ( seq quot: ( obj1 obj2 -- <=> ) -- )
+    [ 0 over length 1 - ] dip quicksort ;
+
+: sort-with! ( seq quot: ( elt -- key ) -- )
+    [ compare ] curry sort! ; inline
+
+: inv-sort-with! ( seq quot: ( elt -- key ) -- )
+    [ compare invert-comparison ] curry sort! ; inline
+
+: natural-sort! ( seq -- )
+    [ <=> ] sort! ;