]> gitweb.factorcode.org Git - factor.git/commitdiff
Make it into a stable sort
authorSlava Pestov <slava@slava-pestovs-macbook-pro.local>
Wed, 16 Jul 2008 04:37:09 +0000 (23:37 -0500)
committerSlava Pestov <slava@slava-pestovs-macbook-pro.local>
Wed, 16 Jul 2008 04:37:09 +0000 (23:37 -0500)
core/sorting/sorting-docs.factor
core/sorting/sorting-tests.factor
core/sorting/sorting.factor

index e55d1eb1504fb4d7a09fc443efb131d0890d0cb3..18bc7f14cf6b7bf258c1ce5878a0b445d9272b3e 100644 (file)
@@ -3,6 +3,10 @@ sequences math.order ;
 IN: sorting
 
 ARTICLE: "sequences-sorting" "Sorting sequences"
+"The " { $vocab-link "sorting" } " vocabulary implements the merge-sort algorithm. It runs in " { $snippet "O(n log n)" } " time, and is a " { $emphasis "stable" } " sort, meaning that the order of equal elements is preserved."
+$nl
+"The algorithm only allocates two additional arrays, both the size of the input sequence, and uses iteration rather than recursion, and thus is suitable for sorting large sequences."
+$nl
 "Sorting combinators all take comparator quotations with stack effect " { $snippet "( elt1 elt2 -- <=> )" } ", where the output value is one of the three " { $link "order-specifiers" } "."
 $nl
 "Sorting a sequence with a custom comparator:"
index 5f3dab14bcf24e304773047727475ae5c0d89739..63e193c89fd13fc6babe39e70e22a53588312bed 100755 (executable)
@@ -18,3 +18,9 @@ unit-test
 ] unit-test
 
 [ ] [ { 1 2 } [ 2drop 1 ] sort drop ] unit-test
+
+! Is it a stable sort?
+[ t ] [ { { 1 "a" } { 1 "b" } { 1 "c" } } dup sort-keys = ] unit-test
+
+[ { { 1 "a" } { 1 "b" } { 1 "c" } { 1 "e" } { 2 "d" } } ]
+[ { { 1 "a" } { 1 "b" } { 1 "c" } { 2 "d" } { 1 "e" } } sort-keys ] unit-test
index a93a30e7f2682b1d2bfda80e189a108dbb53e32c..8b84ea8fe0d9ad517d499e671ca31ac439e99b4f 100755 (executable)
@@ -50,13 +50,13 @@ TUPLE: merge
 : dump-r  [ [ from2>> ] [ to2>> ] [ seq>> ] tri ] [ accum>> ] bi dump ; inline
 : l-next  [ [ l-elt ] [ [ 1+ ] change-from1 drop ] bi ] [ accum>> ] bi push ; inline
 : r-next  [ [ r-elt ] [ [ 1+ ] change-from2 drop ] bi ] [ accum>> ] bi push ; inline
-: decide  [ [ l-elt ] [ r-elt ] bi ] dip call +lt+ eq? ; inline
+: decide  [ [ l-elt ] [ r-elt ] bi ] dip call +gt+ eq? ; inline
 
 : (merge) ( merge quot -- )
-    over l-done? [ drop dump-r ] [
-        over r-done? [ drop dump-l ] [
+    over r-done? [ drop dump-l ] [
+        over l-done? [ drop dump-r ] [
             2dup decide
-            [ over l-next ] [ over r-next ] if
+            [ over r-next ] [ over l-next ] if
             (merge)
         ] if
     ] if ; inline