1 ! Copyright (C) 2008 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: kernel sequences sequences.private accessors math
4 math.order combinators hints arrays ;
9 : midpoint ( seq -- elt )
10 [ midpoint@ ] keep nth-unsafe ; inline
12 : decide ( quot seq -- quot seq <=> )
13 [ midpoint swap call ] 2keep rot ; inline
15 : finish ( quot slice -- i elt )
16 [ [ from>> ] [ midpoint@ ] bi + ] [ seq>> ] bi
17 [ drop ] [ dup ] [ ] tri* nth ; inline
19 : (search) ( quot: ( elt -- <=> ) seq -- i elt )
25 { +lt+ [ dup midpoint@ head-slice (search) ] }
26 { +gt+ [ dup midpoint@ tail-slice (search) ] }
28 ] if ; inline recursive
32 : search ( seq quot -- i elt )
33 over empty? [ 2drop f f ] [ swap <flat-slice> (search) ] if ;
36 : natural-search ( obj seq -- i elt )
39 HINTS: natural-search array ;
41 : sorted-index ( obj seq -- i )
44 : sorted-member? ( obj seq -- ? )
45 dupd natural-search nip = ;
47 : sorted-memq? ( obj seq -- ? )
48 dupd natural-search nip eq? ;