Paste: Quicksort
Author: | Rich |
Mode: | factor |
Date: | Sun, 23 Aug 2009 23:58:13 |
Plain Text |
USING: kernel combinators combinators.short-circuit generalizations
sequences arrays math ;
IN: qsort
: choose-pivot ( seq -- pivot ) 0 swap nth ;
: partition ( pivot seq -- <lowslice> <highslice> )
dup length 1 - 0 0 rot
[ 2dup <= ] [
{
{ [ over 5 npick nth 6 npick < ] [
2over 6 npick exchange
[ [ 1 + ] bi@ ] dip ] }
{ [ over 5 npick nth 6 npick > ] [
2dup 6 npick exchange
1 - ] }
[ [ 1 + ] dip ]
} cond
] while
drop
[ drop 0 spin <slice> ]
[ nip over length rot <slice> ] 3bi rot drop
;
: insertion-sort ( seq -- )
1
over length 1 -
[
2dup swap nth 2over
[ 3dup
{ [ 2nip 0 > ]
[ 1 - swap nth < ]
} 3&& ]
[
dup 1 - pick nth 2over swap set-nth
1 -
] while
swap set-nth
1 +
] times
2drop
;
: qsort ( seq -- )
dup length 8 < [
insertion-sort
] [
dup choose-pivot swap partition
[ qsort ] bi@
] if
; recursive
Author: | Rich |
Mode: | factor |
Date: | Mon, 24 Aug 2009 00:14:32 |
Plain Text |
USING: kernel combinators combinators.short-circuit generalizations
sequences arrays math fry ;
IN: qsort
: choose-pivot ( seq -- pivot ) 0 swap nth ;
: insertion-sort ( seq -- )
1
over length 1 -
[
2dup swap nth 2over
[ 3dup
{ [ 2nip 0 > ]
[ 1 - swap nth < ]
} 3&& ]
[
dup 1 - pick nth 2over swap set-nth
1 -
] while
swap set-nth
1 +
] times
2drop
;
: qsort ( seq -- )
dup length 8 < [
insertion-sort
] [
dup choose-pivot '[ _ < ] partition
[ qsort ] bi@
] if
; recursive
New Annotation