1 ------------------------------------------------------------------------------
3 -- GNAT RUN-TIME COMPONENTS --
5 -- GNAT.BINARY_SEARCH --
9 -- Copyright (C) 2022-2023, AdaCore --
11 -- GNAT is free software; you can redistribute it and/or modify it under --
12 -- terms of the GNU General Public License as published by the Free Soft- --
13 -- ware Foundation; either version 3, or (at your option) any later ver- --
14 -- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE. --
18 -- As a special exception under Section 7 of GPL version 3, you are granted --
19 -- additional permissions described in the GCC Runtime Library Exception, --
20 -- version 3.1, as published by the Free Software Foundation. --
22 -- You should have received a copy of the GNU General Public License and --
23 -- a copy of the GCC Runtime Library Exception along with this program; --
24 -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
25 -- <http://www.gnu.org/licenses/>. --
26 ------------------------------------------------------------------------------
28 package body GNAT
.Binary_Search
is
31 (First
, Last
, Start
: Index_Type
;
32 Element
: Element_Type
) return Index_Type
'Base is
37 (Index
: Index_Type
; Element
: Element_Type
) return Boolean
38 is (Before
(Get
(Index
), Element
)) with Inline_Always
;
40 function Find
is new Binary_Search
.Leftmost
41 (Index_Type
, Element_Type
, Before
);
43 return Find
(First
, Last
, Start
, Element
);
49 (Element
: Element_Type
; Index
: Index_Type
) return Boolean
50 is (Before
(Element
, Get
(Index
))) with Inline_Always
;
52 function Find
is new Rightmost
(Index_Type
, Element_Type
, Before
);
54 return Find
(First
, Last
, Start
, Element
);
64 (First
, Last
, Start
: Index_Type
;
65 Element
: Element_Type
) return Index_Type
'Base
67 L
: Index_Type
:= First
;
68 R
: Index_Type
:= Index_Type
'Succ (Last
);
69 M
: Index_Type
:= Start
;
73 if Before
(M
, Element
) then
74 L
:= Index_Type
'Succ (M
);
83 (Index_Type
'Pos (R
) - Index_Type
'Pos (L
)) / 2);
95 (First
, Last
, Start
: Index_Type
;
96 Element
: Element_Type
) return Index_Type
'Base
98 L
: Index_Type
:= First
;
99 R
: Index_Type
:= Index_Type
'Succ (Last
);
100 M
: Index_Type
:= Start
;
106 if Before
(Element
, M
) then
109 L
:= Index_Type
'Succ (M
);
115 (Index_Type
'Pos (L
) +
116 (Index_Type
'Pos (R
) - Index_Type
'Pos (L
)) / 2);
120 return Index_Type
'Pred (R
);
123 end GNAT
.Binary_Search
;