Binary search: Difference between revisions

Content added Content deleted
(Binary search in BASIC256)
m (syntax highlighting fixup automation)
Line 148: Line 148:


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>F binary_search(l, value)
<syntaxhighlight lang=11l>F binary_search(l, value)
V low = 0
V low = 0
V high = l.len - 1
V high = l.len - 1
Line 159: Line 159:
E
E
R mid
R mid
R -1</lang>
R -1</syntaxhighlight>


=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
<lang 360asm>* Binary search 05/03/2017
<syntaxhighlight lang=360asm>* Binary search 05/03/2017
BINSEAR CSECT
BINSEAR CSECT
USING BINSEAR,R13 base register
USING BINSEAR,R13 base register
Line 232: Line 232:
XDEC DS CL12 temp
XDEC DS CL12 temp
YREGS
YREGS
END BINSEAR</lang>
END BINSEAR</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 247: Line 247:
Test code is included, which will loop through the values [0..255] and report for each number whether it was in the array or not.
Test code is included, which will loop through the values [0..255] and report for each number whether it was in the array or not.


<lang 8080asm> org 100h ; Entry for test code
<syntaxhighlight lang=8080asm> org 100h ; Entry for test code
jmp test
jmp test


Line 349: Line 349:


rst 0
rst 0
</syntaxhighlight>
</lang>
=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<lang AArch64 Assembly>
<syntaxhighlight lang=AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program binSearch64.s */
/* program binSearch64.s */
Line 589: Line 589:
/* for this file see task include a file in language AArch64 assembly */
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
<pre>
<pre>
Value find at index : 0
Value find at index : 0
Line 604: Line 604:
=={{header|ACL2}}==
=={{header|ACL2}}==


<lang Lisp>(defun defarray (name size initial-element)
<syntaxhighlight lang=Lisp>(defun defarray (name size initial-element)
(cons name
(cons name
(compress1 name
(compress1 name
Line 664: Line 664:
(populate-array-ordered
(populate-array-ordered
(defarray 'haystack *dim* 0)
(defarray 'haystack *dim* 0)
*dim*)))</lang>
*dim*)))</syntaxhighlight>


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>INT FUNC BinarySearch(INT ARRAY a INT len,value)
<syntaxhighlight lang=Action!>INT FUNC BinarySearch(INT ARRAY a INT len,value)
INT low,high,mid
INT low,high,mid


Line 712: Line 712:
Test(a,8,10)
Test(a,8,10)
Test(a,8,7)
Test(a,8,7)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Binary_search.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Binary_search.png Screenshot from Atari 8-bit computer]
Line 727: Line 727:
Both solutions are generic. The element can be of any comparable type (such that the operation < is visible in the instantiation scope of the function Search). Note that the completion condition is different from one given in the pseudocode example above. The example assumes that the array index type does not overflow when mid is incremented or decremented beyond the corresponding array bound. This is a wrong assumption for Ada, where array bounds can start or end at the very first or last value of the index type. To deal with this, the exit condition is rather directly expressed as crossing the corresponding array bound by the coming interval middle.
Both solutions are generic. The element can be of any comparable type (such that the operation < is visible in the instantiation scope of the function Search). Note that the completion condition is different from one given in the pseudocode example above. The example assumes that the array index type does not overflow when mid is incremented or decremented beyond the corresponding array bound. This is a wrong assumption for Ada, where array bounds can start or end at the very first or last value of the index type. To deal with this, the exit condition is rather directly expressed as crossing the corresponding array bound by the coming interval middle.
;Recursive:
;Recursive:
<lang ada>with Ada.Text_IO; use Ada.Text_IO;
<syntaxhighlight lang=ada>with Ada.Text_IO; use Ada.Text_IO;


procedure Test_Recursive_Binary_Search is
procedure Test_Recursive_Binary_Search is
Line 780: Line 780:
Test ((2, 4, 6, 8, 9), 9);
Test ((2, 4, 6, 8, 9), 9);
Test ((2, 4, 6, 8, 9), 5);
Test ((2, 4, 6, 8, 9), 5);
end Test_Recursive_Binary_Search;</lang>
end Test_Recursive_Binary_Search;</syntaxhighlight>
;Iterative:
;Iterative:
<lang ada>with Ada.Text_IO; use Ada.Text_IO;
<syntaxhighlight lang=ada>with Ada.Text_IO; use Ada.Text_IO;


procedure Test_Binary_Search is
procedure Test_Binary_Search is
Line 837: Line 837:
Test ((2, 4, 6, 8, 9), 9);
Test ((2, 4, 6, 8, 9), 9);
Test ((2, 4, 6, 8, 9), 5);
Test ((2, 4, 6, 8, 9), 5);
end Test_Binary_Search;</lang>
end Test_Binary_Search;</syntaxhighlight>
Sample output:
Sample output:
<pre>
<pre>
Line 849: Line 849:


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
<lang algol68>BEGIN
<syntaxhighlight lang=algol68>BEGIN
MODE ELEMENT = STRING;
MODE ELEMENT = STRING;
Line 897: Line 897:
test search(recursive binary search, test cases)
test search(recursive binary search, test cases)
)
)
END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
Shows iterative search output - recursive search output is the same.
Shows iterative search output - recursive search output is the same.
Line 909: Line 909:
=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
Ieterative and recursive binary search procedures, from the pseudo code. Finds the left most occurance/insertion point.
Ieterative and recursive binary search procedures, from the pseudo code. Finds the left most occurance/insertion point.
<lang algolw>begin % binary search %
<syntaxhighlight lang=algolw>begin % binary search %
% recursive binary search, left most insertion point %
% recursive binary search, left most insertion point %
integer procedure binarySearchLR ( integer array A ( * )
integer procedure binarySearchLR ( integer array A ( * )
Line 957: Line 957:
end for_s
end for_s
end
end
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 973: Line 973:
{{works with|Dyalog APL}}
{{works with|Dyalog APL}}


<lang APL>binsrch←{
<syntaxhighlight lang=APL>binsrch←{
⎕IO(⍺{ ⍝ first lower bound is start of array
⎕IO(⍺{ ⍝ first lower bound is start of array
⍵<⍺:⍬ ⍝ if high < low, we didn't find it
⍵<⍺:⍬ ⍝ if high < low, we didn't find it
Line 982: Line 982:
}⍵)⎕IO+(≢⍺)-1 ⍝ first higher bound is top of array
}⍵)⎕IO+(≢⍺)-1 ⍝ first higher bound is top of array
}
}
</syntaxhighlight>
</lang>


=={{header|AppleScript}}==
=={{header|AppleScript}}==


<lang applescript>on binarySearch(n, theList, l, r)
<syntaxhighlight lang=applescript>on binarySearch(n, theList, l, r)
repeat until (l = r)
repeat until (l = r)
set m to (l + r) div 2
set m to (l + r) div 2
Line 1,010: Line 1,010:


set theList to {1, 2, 3, 3, 5, 7, 7, 8, 9, 10, 11, 12}
set theList to {1, 2, 3, 3, 5, 7, 7, 8, 9, 10, 11, 12}
return test(7, theList, 4, 11) & linefeed & test(7, theList, 7, 12) & linefeed & test(7, theList, 1, 5)</lang>
return test(7, theList, 4, 11) & linefeed & test(7, theList, 7, 12) & linefeed & test(7, theList, 1, 5)</syntaxhighlight>


{{output}}
{{output}}
Line 1,020: Line 1,020:
=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<lang ARM Assembly>
<syntaxhighlight lang=ARM Assembly>


/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
Line 1,297: Line 1,297:
iMagicNumber: .int 0xCCCCCCCD
iMagicNumber: .int 0xCCCCCCCD


</syntaxhighlight>
</lang>


=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>binarySearch: function [arr,val,low,high][
<syntaxhighlight lang=rebol>binarySearch: function [arr,val,low,high][
if high < low -> return ø
if high < low -> return ø
mid: shr low+high 1
mid: shr low+high 1
Line 1,320: Line 1,320:
if? not? null? i -> print ["found" v "at index:" i]
if? not? null? i -> print ["found" v "at index:" i]
else -> print [v "not found"]
else -> print [v "not found"]
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 1,331: Line 1,331:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>array := "1,2,4,6,8,9"
<syntaxhighlight lang=AutoHotkey>array := "1,2,4,6,8,9"
StringSplit, A, array, `, ; creates associative array
StringSplit, A, array, `, ; creates associative array
MsgBox % x := BinarySearch(A, 4, 1, A0) ; Recursive
MsgBox % x := BinarySearch(A, 4, 1, A0) ; Recursive
Line 1,363: Line 1,363:
}
}
Return not_found
Return not_found
}</lang>
}</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
Line 1,370: Line 1,370:
{{works with|Nawk}}
{{works with|Nawk}}
'''Recursive'''
'''Recursive'''
<lang awk>function binary_search(array, value, left, right, middle) {
<syntaxhighlight lang=awk>function binary_search(array, value, left, right, middle) {
if (right < left) return 0
if (right < left) return 0
middle = int((right + left) / 2)
middle = int((right + left) / 2)
Line 1,377: Line 1,377:
return binary_search(array, value, left, middle - 1)
return binary_search(array, value, left, middle - 1)
return binary_search(array, value, middle + 1, right)
return binary_search(array, value, middle + 1, right)
}</lang>
}</syntaxhighlight>
'''Iterative'''
'''Iterative'''
<lang awk>function binary_search(array, value, left, right, middle) {
<syntaxhighlight lang=awk>function binary_search(array, value, left, right, middle) {
while (left <= right) {
while (left <= right) {
middle = int((right + left) / 2)
middle = int((right + left) / 2)
Line 1,387: Line 1,387:
}
}
return 0
return 0
}</lang>
}</syntaxhighlight>


=={{header|Axe}}==
=={{header|Axe}}==
Line 1,394: Line 1,394:
BSEARCH takes 3 arguments: a pointer to the start of the data, the data to find, and the length of the array in bytes.
BSEARCH takes 3 arguments: a pointer to the start of the data, the data to find, and the length of the array in bytes.


<lang axe>Lbl BSEARCH
<syntaxhighlight lang=axe>Lbl BSEARCH
0→L
0→L
r₃-1→H
r₃-1→H
Line 1,409: Line 1,409:
End
End
-1
-1
Return</lang>
Return</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==
Line 1,415: Line 1,415:
{{works with|FreeBASIC}}
{{works with|FreeBASIC}}
{{works with|RapidQ}}
{{works with|RapidQ}}
<lang freebasic>FUNCTION binary_search ( array() AS Integer, value AS Integer, lo AS Integer, hi AS Integer) AS Integer
<syntaxhighlight lang=freebasic>FUNCTION binary_search ( array() AS Integer, value AS Integer, lo AS Integer, hi AS Integer) AS Integer
DIM middle AS Integer
DIM middle AS Integer
Line 1,431: Line 1,431:
END SELECT
END SELECT
END IF
END IF
END FUNCTION</lang>
END FUNCTION</syntaxhighlight>
'''Iterative'''
'''Iterative'''
{{works with|FreeBASIC}}
{{works with|FreeBASIC}}
{{works with|RapidQ}}
{{works with|RapidQ}}
<lang freebasic>FUNCTION binary_search ( array() AS Integer, value AS Integer, lo AS Integer, hi AS Integer) AS Integer
<syntaxhighlight lang=freebasic>FUNCTION binary_search ( array() AS Integer, value AS Integer, lo AS Integer, hi AS Integer) AS Integer
DIM middle AS Integer
DIM middle AS Integer
Line 1,451: Line 1,451:
WEND
WEND
binary_search = 0
binary_search = 0
END FUNCTION</lang>
END FUNCTION</syntaxhighlight>
'''Testing the function'''
'''Testing the function'''


The following program can be used to test both recursive and iterative version.
The following program can be used to test both recursive and iterative version.
<lang freebasic>SUB search (array() AS Integer, value AS Integer)
<syntaxhighlight lang=freebasic>SUB search (array() AS Integer, value AS Integer)
DIM idx AS Integer
DIM idx AS Integer


Line 1,477: Line 1,477:
search test(), 4
search test(), 4
search test(), 8
search test(), 8
search test(), 20</lang>
search test(), 20</syntaxhighlight>
Output:
Output:
Value 4 not found
Value 4 not found
Line 1,484: Line 1,484:


==={{header|ASIC}}===
==={{header|ASIC}}===
<lang basic>
<syntaxhighlight lang=basic>
REM Binary search
REM Binary search
DIM A(10)
DIM A(10)
Line 1,545: Line 1,545:
ENDIF
ENDIF
RETURN
RETURN
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,553: Line 1,553:


==={{header|BBC BASIC}}===
==={{header|BBC BASIC}}===
<lang bbcbasic> DIM array%(9)
<syntaxhighlight lang=bbcbasic> DIM array%(9)
array%() = 7, 14, 21, 28, 35, 42, 49, 56, 63, 70
array%() = 7, 14, 21, 28, 35, 42, 49, 56, 63, 70
Line 1,575: Line 1,575:
H% /= 2
H% /= 2
UNTIL H%=0
UNTIL H%=0
IF S%=A%(B%) THEN = B% ELSE = -1</lang>
IF S%=A%(B%) THEN = B% ELSE = -1</syntaxhighlight>


==={{header|FreeBASIC}}===
==={{header|FreeBASIC}}===
<lang freebasic>function binsearch( array() as integer, target as integer ) as integer
<syntaxhighlight lang=freebasic>function binsearch( array() as integer, target as integer ) as integer
'returns the index of the target number, or -1 if it is not in the array
'returns the index of the target number, or -1 if it is not in the array
dim as uinteger lo = lbound(array), hi = ubound(array), md = (lo + hi)\2
dim as uinteger lo = lbound(array), hi = ubound(array), md = (lo + hi)\2
Line 1,589: Line 1,589:
wend
wend
return -1
return -1
end function</lang>
end function</syntaxhighlight>


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC>100 PROGRAM "Search.bas"
<syntaxhighlight lang=IS-BASIC>100 PROGRAM "Search.bas"
110 RANDOMIZE
110 RANDOMIZE
120 NUMERIC ARR(1 TO 20)
120 NUMERIC ARR(1 TO 20)
Line 1,618: Line 1,618:
340 LOOP WHILE BO<=UP AND T(K)<>N
340 LOOP WHILE BO<=UP AND T(K)<>N
350 IF BO<=UP THEN LET SEARCH=K
350 IF BO<=UP THEN LET SEARCH=K
360 END DEF</lang>
360 END DEF</syntaxhighlight>


==={{header|Minimal BASIC}}===
==={{header|Minimal BASIC}}===
Line 1,624: Line 1,624:
{{works with|Commodore BASIC|3.5}}
{{works with|Commodore BASIC|3.5}}
{{works with|Nascom ROM BASIC|4.7}}
{{works with|Nascom ROM BASIC|4.7}}
<lang gwbasic>
<syntaxhighlight lang=gwbasic>
10 REM Binary search
10 REM Binary search
20 LET N = 10
20 LET N = 10
Line 1,671: Line 1,671:
670 LET I1 = -1
670 LET I1 = -1
680 RETURN
680 RETURN
</syntaxhighlight>
</lang>


=={{header|BASIC256}}==
=={{header|BASIC256}}==
====Recursive Solution====
====Recursive Solution====
<lang BASIC256>function binarySearchR(array, valor, lb, ub)
<syntaxhighlight lang=BASIC256>function binarySearchR(array, valor, lb, ub)
if ub < lb then
if ub < lb then
return false
return false
Line 1,684: Line 1,684:
if valor = array[mitad] then return mitad
if valor = array[mitad] then return mitad
end if
end if
end function</lang>
end function</syntaxhighlight>


====Iterative Solution====
====Iterative Solution====
<lang BASIC256>function binarySearchI(array, valor)
<syntaxhighlight lang=BASIC256>function binarySearchI(array, valor)
lb = array[?,]
lb = array[?,]
ub = array[?]
ub = array[?]
Line 1,703: Line 1,703:
end while
end while
return false
return false
end function</lang>
end function</syntaxhighlight>
'''Test:'''
'''Test:'''
<lang BASIC256>items = 10e5
<syntaxhighlight lang=BASIC256>items = 10e5
dim array(items)
dim array(items)
for n = 0 to items-1 : array[n] = n : next n
for n = 0 to items-1 : array[n] = n : next n
Line 1,715: Line 1,715:
print binarySearchR(array, 3, array[?,], array[?])
print binarySearchR(array, 3, array[?,], array[?])
print msec - t1; " millisec"
print msec - t1; " millisec"
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>3
<pre>3
Line 1,723: Line 1,723:


=={{header|Batch File}}==
=={{header|Batch File}}==
<lang windowsnt>
<syntaxhighlight lang=windowsnt>
@echo off & setlocal enabledelayedexpansion
@echo off & setlocal enabledelayedexpansion


Line 1,772: Line 1,772:
echo . binchop required !b! iterations
echo . binchop required !b! iterations
endlocal & exit /b 0
endlocal & exit /b 0
</syntaxhighlight>
</lang>


=={{header|BQN}}==
=={{header|BQN}}==
Line 1,778: Line 1,778:
BQN has two builtin functions for binary search: <code>⍋</code>(Bins Up) and <code>⍒</code>(Bins Down). This is a recursive method.
BQN has two builtin functions for binary search: <code>⍋</code>(Bins Up) and <code>⍒</code>(Bins Down). This is a recursive method.


<lang bqn>BSearch ← {
<syntaxhighlight lang=bqn>BSearch ← {
BS ⟨a, value⟩:
BS ⟨a, value⟩:
BS ⟨a, value, 0, ¯1+≠a⟩;
BS ⟨a, value, 0, ¯1+≠a⟩;
Line 1,791: Line 1,791:
}
}


•Show BSearch ⟨8‿30‿35‿45‿49‿77‿79‿82‿87‿97, 97⟩</lang>
•Show BSearch ⟨8‿30‿35‿45‿49‿77‿79‿82‿87‿97, 97⟩</syntaxhighlight>
<lang>9</lang>
<syntaxhighlight lang=text>9</syntaxhighlight>


=={{header|Brat}}==
=={{header|Brat}}==
<lang brat>binary_search = { search_array, value, low, high |
<syntaxhighlight lang=brat>binary_search = { search_array, value, low, high |
true? high < low
true? high < low
{ null }
{ null }
Line 1,825: Line 1,825:
null? index
null? index
{ p "Not found" }
{ p "Not found" }
{ p "Found at index: #{index}" }</lang>
{ p "Found at index: #{index}" }</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==


<lang c>#include <stdio.h>
<syntaxhighlight lang=c>#include <stdio.h>


int bsearch (int *a, int n, int x) {
int bsearch (int *a, int n, int x) {
Line 1,881: Line 1,881:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>
{{output}}
{{output}}
<pre>
<pre>
Line 1,890: Line 1,890:
=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
'''Recursive'''
'''Recursive'''
<lang csharp>namespace Search {
<syntaxhighlight lang=csharp>namespace Search {
using System;
using System;


Line 1,960: Line 1,960:
}
}
}
}
}</lang>
}</syntaxhighlight>
'''Iterative'''
'''Iterative'''
<lang csharp>namespace Search {
<syntaxhighlight lang=csharp>namespace Search {
using System;
using System;


Line 2,034: Line 2,034:
}
}
}
}
}</lang>
}</syntaxhighlight>
'''Example'''
'''Example'''
<lang csharp>//#define UseRecursiveSearch
<syntaxhighlight lang=csharp>//#define UseRecursiveSearch


using System;
using System;
Line 2,078: Line 2,078:
#endif
#endif
}
}
}</lang>
}</syntaxhighlight>


'''Output'''
'''Output'''
Line 2,117: Line 2,117:
=={{header|C++}}==
=={{header|C++}}==
'''Recursive'''
'''Recursive'''
<lang cpp>
<syntaxhighlight lang=cpp>
template <class T> int binsearch(const T array[], int low, int high, T value) {
template <class T> int binsearch(const T array[], int low, int high, T value) {
if (high < low) {
if (high < low) {
Line 2,143: Line 2,143:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
'''Iterative'''
'''Iterative'''
<lang cpp>template <class T>
<syntaxhighlight lang=cpp>template <class T>
int binSearch(const T arr[], int len, T what) {
int binSearch(const T arr[], int len, T what) {
int low = 0;
int low = 0;
Line 2,159: Line 2,159:
}
}
return -1; // indicate not found
return -1; // indicate not found
}</lang>
}</syntaxhighlight>
'''Library'''
'''Library'''
C++'s Standard Template Library has four functions for binary search, depending on what information you want to get. They all need<lang cpp>#include <algorithm></lang>
C++'s Standard Template Library has four functions for binary search, depending on what information you want to get. They all need<syntaxhighlight lang=cpp>#include <algorithm></syntaxhighlight>


The <code>lower_bound()</code> function returns an iterator to the first position where a value could be inserted without violating the order; i.e. the first element equal to the element you want, or the place where it would be inserted.
The <code>lower_bound()</code> function returns an iterator to the first position where a value could be inserted without violating the order; i.e. the first element equal to the element you want, or the place where it would be inserted.
<lang cpp>int *ptr = std::lower_bound(array, array+len, what); // a custom comparator can be given as fourth arg</lang>
<syntaxhighlight lang=cpp>int *ptr = std::lower_bound(array, array+len, what); // a custom comparator can be given as fourth arg</syntaxhighlight>


The <code>upper_bound()</code> function returns an iterator to the last position where a value could be inserted without violating the order; i.e. one past the last element equal to the element you want, or the place where it would be inserted.
The <code>upper_bound()</code> function returns an iterator to the last position where a value could be inserted without violating the order; i.e. one past the last element equal to the element you want, or the place where it would be inserted.
<lang cpp>int *ptr = std::upper_bound(array, array+len, what); // a custom comparator can be given as fourth arg</lang>
<syntaxhighlight lang=cpp>int *ptr = std::upper_bound(array, array+len, what); // a custom comparator can be given as fourth arg</syntaxhighlight>


The <code>equal_range()</code> function returns a pair of the results of <code>lower_bound()</code> and <code>upper_bound()</code>.
The <code>equal_range()</code> function returns a pair of the results of <code>lower_bound()</code> and <code>upper_bound()</code>.
<lang cpp>std::pair<int *, int *> bounds = std::equal_range(array, array+len, what); // a custom comparator can be given as fourth arg</lang>
<syntaxhighlight lang=cpp>std::pair<int *, int *> bounds = std::equal_range(array, array+len, what); // a custom comparator can be given as fourth arg</syntaxhighlight>
Note that the difference between the bounds is the number of elements equal to the element you want.
Note that the difference between the bounds is the number of elements equal to the element you want.


The <code>binary_search()</code> function returns true or false for whether an element equal to the one you want exists in the array. It does not give you any information as to where it is.
The <code>binary_search()</code> function returns true or false for whether an element equal to the one you want exists in the array. It does not give you any information as to where it is.
<lang cpp>bool found = std::binary_search(array, array+len, what); // a custom comparator can be given as fourth arg</lang>
<syntaxhighlight lang=cpp>bool found = std::binary_search(array, array+len, what); // a custom comparator can be given as fourth arg</syntaxhighlight>


=={{header|Chapel}}==
=={{header|Chapel}}==


'''iterative''' -- almost a direct translation of the pseudocode
'''iterative''' -- almost a direct translation of the pseudocode
<lang chapel>proc binsearch(A:[], value) {
<syntaxhighlight lang=chapel>proc binsearch(A:[], value) {
var low = A.domain.dim(1).low;
var low = A.domain.dim(1).low;
var high = A.domain.dim(1).high;
var high = A.domain.dim(1).high;
Line 2,195: Line 2,195:
}
}


writeln(binsearch([3, 4, 6, 9, 11], 9));</lang>
writeln(binsearch([3, 4, 6, 9, 11], 9));</syntaxhighlight>


{{out}}
{{out}}
Line 2,202: Line 2,202:
=={{header|Clojure}}==
=={{header|Clojure}}==
'''Recursive'''
'''Recursive'''
<lang clojure>(defn bsearch
<syntaxhighlight lang=clojure>(defn bsearch
([coll t]
([coll t]
(bsearch coll 0 (dec (count coll)) t))
(bsearch coll 0 (dec (count coll)) t))
Line 2,217: Line 2,217:
; we've found our target
; we've found our target
; so return its index
; so return its index
(= mth t) m)))))</lang>
(= mth t) m)))))</syntaxhighlight>


=={{header|CLU}}==
=={{header|CLU}}==
<lang clu>% Binary search in an array
<syntaxhighlight lang=clu>% Binary search in an array
% If the item is found, returns `true' and the index;
% If the item is found, returns `true' and the index;
% if the item is not found, returns `false' and the leftmost insertion point
% if the item is not found, returns `false' and the leftmost insertion point
Line 2,266: Line 2,266:
end
end
end
end
end start_up</lang>
end start_up</syntaxhighlight>
{{out}}
{{out}}
<pre>1 not found, would be inserted at location 1
<pre>1 not found, would be inserted at location 1
Line 2,291: Line 2,291:
=={{header|COBOL}}==
=={{header|COBOL}}==
COBOL's <code>SEARCH ALL</code> statement is implemented as a binary search on most implementations.
COBOL's <code>SEARCH ALL</code> statement is implemented as a binary search on most implementations.
<lang cobol> >>SOURCE FREE
<syntaxhighlight lang=cobol> >>SOURCE FREE
IDENTIFICATION DIVISION.
IDENTIFICATION DIVISION.
PROGRAM-ID. binary-search.
PROGRAM-ID. binary-search.
Line 2,308: Line 2,308:
END-SEARCH
END-SEARCH
.
.
END PROGRAM binary-search.</lang>
END PROGRAM binary-search.</syntaxhighlight>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
'''Recursive'''
'''Recursive'''
<lang coffeescript>binarySearch = (xs, x) ->
<syntaxhighlight lang=coffeescript>binarySearch = (xs, x) ->
do recurse = (low = 0, high = xs.length - 1) ->
do recurse = (low = 0, high = xs.length - 1) ->
mid = Math.floor (low + high) / 2
mid = Math.floor (low + high) / 2
Line 2,319: Line 2,319:
when xs[mid] > x then recurse low, mid - 1
when xs[mid] > x then recurse low, mid - 1
when xs[mid] < x then recurse mid + 1, high
when xs[mid] < x then recurse mid + 1, high
else mid</lang>
else mid</syntaxhighlight>
'''Iterative'''
'''Iterative'''
<lang coffeescript>binarySearch = (xs, x) ->
<syntaxhighlight lang=coffeescript>binarySearch = (xs, x) ->
[low, high] = [0, xs.length - 1]
[low, high] = [0, xs.length - 1]
while low <= high
while low <= high
Line 2,329: Line 2,329:
when xs[mid] < x then low = mid + 1
when xs[mid] < x then low = mid + 1
else return mid
else return mid
NaN</lang>
NaN</syntaxhighlight>
'''Test'''
'''Test'''
<lang coffeescript>do (n = 12) ->
<syntaxhighlight lang=coffeescript>do (n = 12) ->
odds = (it for it in [1..n] by 2)
odds = (it for it in [1..n] by 2)
result = (it for it in \
result = (it for it in \
Line 2,338: Line 2,338:
console.assert "#{result}" is "#{[0...odds.length]}"
console.assert "#{result}" is "#{[0...odds.length]}"
console.log "#{odds} are odd natural numbers"
console.log "#{odds} are odd natural numbers"
console.log "#{it} is ordinal of #{odds[it]}" for it in result</lang>
console.log "#{it} is ordinal of #{odds[it]}" for it in result</syntaxhighlight>
Output:
Output:
<pre>1,3,5,7,9,11 are odd natural numbers"
<pre>1,3,5,7,9,11 are odd natural numbers"
Line 2,350: Line 2,350:
=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
'''Iterative'''
'''Iterative'''
<lang lisp>(defun binary-search (value array)
<syntaxhighlight lang=lisp>(defun binary-search (value array)
(let ((low 0)
(let ((low 0)
(high (1- (length array))))
(high (1- (length array))))
Line 2,363: Line 2,363:
(setf low (1+ middle)))
(setf low (1+ middle)))
(t (return middle)))))))</lang>
(t (return middle)))))))</syntaxhighlight>
'''Recursive'''
'''Recursive'''
<lang lisp>(defun binary-search (value array &optional (low 0) (high (1- (length array))))
<syntaxhighlight lang=lisp>(defun binary-search (value array &optional (low 0) (high (1- (length array))))
(if (< high low)
(if (< high low)
nil
nil
Line 2,376: Line 2,376:
(binary-search value array (1+ middle) high))
(binary-search value array (1+ middle) high))
(t middle)))))</lang>
(t middle)))))</syntaxhighlight>


=={{header|Crystal}}==
=={{header|Crystal}}==
'''Recursive'''
'''Recursive'''
<lang ruby>class Array
<syntaxhighlight lang=ruby>class Array
def binary_search(val, low = 0, high = (size - 1))
def binary_search(val, low = 0, high = (size - 1))
return nil if high < low
return nil if high < low
Line 2,404: Line 2,404:
puts "#{val} not found in array"
puts "#{val} not found in array"
end
end
end</lang>
end</syntaxhighlight>
'''Iterative'''
'''Iterative'''
<lang ruby>class Array
<syntaxhighlight lang=ruby>class Array
def binary_search_iterative(val)
def binary_search_iterative(val)
low, high = 0, size - 1
low, high = 0, size - 1
Line 2,434: Line 2,434:
puts "#{val} not found in array"
puts "#{val} not found in array"
end
end
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,445: Line 2,445:


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio, std.array, std.range, std.traits;
<syntaxhighlight lang=d>import std.stdio, std.array, std.range, std.traits;


/// Recursive.
/// Recursive.
Line 2,485: Line 2,485:
// Standard Binary Search:
// Standard Binary Search:
!items.equalRange(x).empty);
!items.equalRange(x).empty);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre> 1 false false false
<pre> 1 false false false
Line 2,497: Line 2,497:


=={{header|E}}==
=={{header|E}}==
<lang e>/** Returns null if the value is not found. */
<syntaxhighlight lang=e>/** Returns null if the value is not found. */
def binarySearch(collection, value) {
def binarySearch(collection, value) {
var low := 0
var low := 0
Line 2,510: Line 2,510:
}
}
return null
return null
}</lang>
}</syntaxhighlight>


=={{header|EasyLang}}==
=={{header|EasyLang}}==
<lang>func bin_search val . a[] res .
<syntaxhighlight lang=text>func bin_search val . a[] res .
low = 0
low = 0
high = len a[] - 1
high = len a[] - 1
Line 2,530: Line 2,530:
a[] = [ 2 4 6 8 9 ]
a[] = [ 2 4 6 8 9 ]
call bin_search 8 a[] r
call bin_search 8 a[] r
print r</lang>
print r</syntaxhighlight>


=={{header|Eiffel}}==
=={{header|Eiffel}}==
Line 2,536: Line 2,536:
The following solution is based on the one described in: C. A. Furia, B. Meyer, and S. Velder. ''Loop Invariants: Analysis, Classification, and Examples''. ACM Computing Surveys, 46(3), Article 34, January 2014. (Also available at http://arxiv.org/abs/1211.4470). It includes detailed loop invariants and pre- and postconditions, which make the running time linear (instead of logarithmic) when full contract checking is enabled.
The following solution is based on the one described in: C. A. Furia, B. Meyer, and S. Velder. ''Loop Invariants: Analysis, Classification, and Examples''. ACM Computing Surveys, 46(3), Article 34, January 2014. (Also available at http://arxiv.org/abs/1211.4470). It includes detailed loop invariants and pre- and postconditions, which make the running time linear (instead of logarithmic) when full contract checking is enabled.


<lang Eiffel>class
<syntaxhighlight lang=Eiffel>class
APPLICATION
APPLICATION


Line 2,655: Line 2,655:
end
end


end</lang>
end</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>defmodule Binary do
<syntaxhighlight lang=elixir>defmodule Binary do
def search(list, value), do: search(List.to_tuple(list), value, 0, length(list)-1)
def search(list, value), do: search(List.to_tuple(list), value, 0, length(list)-1)
Line 2,679: Line 2,679:
index -> IO.puts "found #{val} at index #{index}"
index -> IO.puts "found #{val} at index #{index}"
end
end
end)</lang>
end)</syntaxhighlight>


{{out}}
{{out}}
Line 2,691: Line 2,691:


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
<lang lisp>
<syntaxhighlight lang=lisp>
(defun binary-search (value array)
(defun binary-search (value array)
(let ((low 0)
(let ((low 0)
Line 2,701: Line 2,701:
((< (aref array middle) value)
((< (aref array middle) value)
(setf low (1+ middle)))
(setf low (1+ middle)))
(t (cl-return middle)))))))</lang>
(t (cl-return middle)))))))</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang Erlang>%% Task: Binary Search algorithm
<syntaxhighlight lang=Erlang>%% Task: Binary Search algorithm
%% Author: Abhay Jain
%% Author: Abhay Jain


Line 2,730: Line 2,730:
Mid
Mid
end
end
end.</lang>
end.</syntaxhighlight>


=={{header|Euphoria}}==
=={{header|Euphoria}}==
===Recursive===
===Recursive===
<lang euphoria>function binary_search(sequence s, object val, integer low, integer high)
<syntaxhighlight lang=euphoria>function binary_search(sequence s, object val, integer low, integer high)
integer mid, cmp
integer mid, cmp
if high < low then
if high < low then
Line 2,749: Line 2,749:
end if
end if
end if
end if
end function</lang>
end function</syntaxhighlight>
===Iterative===
===Iterative===
<lang euphoria>function binary_search(sequence s, object val)
<syntaxhighlight lang=euphoria>function binary_search(sequence s, object val)
integer low, high, mid, cmp
integer low, high, mid, cmp
low = 1
low = 1
Line 2,767: Line 2,767:
end while
end while
return 0 -- not found
return 0 -- not found
end function</lang>
end function</syntaxhighlight>


=={{header|F Sharp|F#}}==
=={{header|F Sharp|F#}}==
Generic recursive version, using #light syntax:
Generic recursive version, using #light syntax:
<lang fsharp>let rec binarySearch (myArray:array<IComparable>, low:int, high:int, value:IComparable) =
<syntaxhighlight lang=fsharp>let rec binarySearch (myArray:array<IComparable>, low:int, high:int, value:IComparable) =
if (high < low) then
if (high < low) then
null
null
Line 2,782: Line 2,782:
binarySearch (myArray, mid+1, high, value)
binarySearch (myArray, mid+1, high, value)
else
else
myArray.[mid]</lang>
myArray.[mid]</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
Factor already includes a binary search in its standard library. The following code offers an interface compatible with the requirement of this task, and returns either the index of the element if it has been found or f otherwise.
Factor already includes a binary search in its standard library. The following code offers an interface compatible with the requirement of this task, and returns either the index of the element if it has been found or f otherwise.
<lang factor>USING: binary-search kernel math.order ;
<syntaxhighlight lang=factor>USING: binary-search kernel math.order ;


: binary-search ( seq elt -- index/f )
: binary-search ( seq elt -- index/f )
[ [ <=> ] curry search ] keep = [ drop f ] unless ;</lang>
[ [ <=> ] curry search ] keep = [ drop f ] unless ;</syntaxhighlight>


=={{header|FBSL}}==
=={{header|FBSL}}==
FBSL has built-in QuickSort() and BSearch() functions:
FBSL has built-in QuickSort() and BSearch() functions:
<lang qbasic>#APPTYPE CONSOLE
<syntaxhighlight lang=qbasic>#APPTYPE CONSOLE


DIM va[], sign = {1, -1}, toggle
DIM va[], sign = {1, -1}, toggle
Line 2,814: Line 2,814:
" in ", GetTickCount() - gtc, " milliseconds"
" in ", GetTickCount() - gtc, " milliseconds"


PAUSE</lang>
PAUSE</syntaxhighlight>
Output:<pre>Loading ... done in 906 milliseconds
Output:<pre>Loading ... done in 906 milliseconds
Sorting ... done in 547 milliseconds
Sorting ... done in 547 milliseconds
Line 2,823: Line 2,823:


'''Iterative:'''
'''Iterative:'''
<lang qbasic>#APPTYPE CONSOLE
<syntaxhighlight lang=qbasic>#APPTYPE CONSOLE


DIM va[]
DIM va[]
Line 2,851: Line 2,851:
WEND
WEND
RETURN -1
RETURN -1
END FUNCTION</lang>
END FUNCTION</syntaxhighlight>
Output:<pre>Loading ... done in 391 milliseconds
Output:<pre>Loading ... done in 391 milliseconds
3141592.65358979 found at index 1000000 in 62 milliseconds
3141592.65358979 found at index 1000000 in 62 milliseconds
Line 2,858: Line 2,858:


'''Recursive:'''
'''Recursive:'''
<lang qbasic>#APPTYPE CONSOLE
<syntaxhighlight lang=qbasic>#APPTYPE CONSOLE


DIM va[]
DIM va[]
Line 2,882: Line 2,882:
END IF
END IF
RETURN midp
RETURN midp
END FUNCTION</lang>
END FUNCTION</syntaxhighlight>
Output:<pre>Loading ... done in 390 milliseconds
Output:<pre>Loading ... done in 390 milliseconds
3141592.65358979 found at index 1000000 in 938 milliseconds
3141592.65358979 found at index 1000000 in 938 milliseconds
Line 2,890: Line 2,890:
=={{header|Forth}}==
=={{header|Forth}}==
This version is designed for maintaining a sorted array. If the item is not found, then then location returned is the proper insertion point for the item. This could be used in an optimized [[Insertion sort]], for example.
This version is designed for maintaining a sorted array. If the item is not found, then then location returned is the proper insertion point for the item. This could be used in an optimized [[Insertion sort]], for example.
<lang forth>defer (compare)
<syntaxhighlight lang=forth>defer (compare)
' - is (compare) \ default to numbers
' - is (compare) \ default to numbers


Line 2,920: Line 2,920:
10 probe \ 0 11
10 probe \ 0 11
11 probe \ -1 11
11 probe \ -1 11
12 probe \ 0 99</lang>
12 probe \ 0 99</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
'''Recursive'''
'''Recursive'''
In ISO Fortran 90 or later use a RECURSIVE function and ARRAY SECTION argument:
In ISO Fortran 90 or later use a RECURSIVE function and ARRAY SECTION argument:
<lang fortran>recursive function binarySearch_R (a, value) result (bsresult)
<syntaxhighlight lang=fortran>recursive function binarySearch_R (a, value) result (bsresult)
real, intent(in) :: a(:), value
real, intent(in) :: a(:), value
integer :: bsresult, mid
integer :: bsresult, mid
Line 2,942: Line 2,942:
bsresult = mid ! SUCCESS!!
bsresult = mid ! SUCCESS!!
end if
end if
end function binarySearch_R</lang>
end function binarySearch_R</syntaxhighlight>
'''Iterative'''
'''Iterative'''
<br>
<br>
In ISO Fortran 90 or later use an ARRAY SECTION POINTER:
In ISO Fortran 90 or later use an ARRAY SECTION POINTER:
<lang fortran>function binarySearch_I (a, value)
<syntaxhighlight lang=fortran>function binarySearch_I (a, value)
integer :: binarySearch_I
integer :: binarySearch_I
real, intent(in), target :: a(:)
real, intent(in), target :: a(:)
Line 2,968: Line 2,968:
end if
end if
end do
end do
end function binarySearch_I</lang>
end function binarySearch_I</syntaxhighlight>


===Iterative, exclusive bounds, three-way test.===
===Iterative, exclusive bounds, three-way test.===
Line 2,979: Line 2,979:
The use of "exclusive" bounds simplifies the adjustment of the bounds: the appropriate bound simply receives the value of P, there is ''no'' + 1 or - 1 adjustment ''at every step''; similarly, the determination of an empty span is easy, and avoiding the risk of integer overflow via (L + R)/2 is achieved at the same time. The "inclusive" bounds version by contrast requires ''two'' manipulations of L and R ''at every step'' - once to see if the span is empty, and a second time to locate the index to test.
The use of "exclusive" bounds simplifies the adjustment of the bounds: the appropriate bound simply receives the value of P, there is ''no'' + 1 or - 1 adjustment ''at every step''; similarly, the determination of an empty span is easy, and avoiding the risk of integer overflow via (L + R)/2 is achieved at the same time. The "inclusive" bounds version by contrast requires ''two'' manipulations of L and R ''at every step'' - once to see if the span is empty, and a second time to locate the index to test.
<lang Fortran> INTEGER FUNCTION FINDI(X,A,N) !Binary chopper. Find i such that X = A(i)
<syntaxhighlight lang=Fortran> INTEGER FUNCTION FINDI(X,A,N) !Binary chopper. Find i such that X = A(i)
Careful: it is surprisingly difficult to make this neat, due to vexations when N = 0 or 1.
Careful: it is surprisingly difficult to make this neat, due to vexations when N = 0 or 1.
REAL X,A(*) !Where is X in array A(1:N)?
REAL X,A(*) !Where is X in array A(1:N)?
Line 2,998: Line 2,998:
Curse it!
Curse it!
5 FINDI = -L !X is not found. Insert it at L + 1, i.e. at A(1 - FINDI).
5 FINDI = -L !X is not found. Insert it at L + 1, i.e. at A(1 - FINDI).
END FUNCTION FINDI !A's values need not be all different, merely in order. </lang>
END FUNCTION FINDI !A's values need not be all different, merely in order. </syntaxhighlight>


[[File:BinarySearch.Flowchart.png]]
[[File:BinarySearch.Flowchart.png]]
Line 3,010: Line 3,010:


====An alternative version====
====An alternative version====
<lang Fortran> INTEGER FUNCTION FINDI(X,A,N) !Binary chopper. Find i such that X = A(i)
<syntaxhighlight lang=Fortran> INTEGER FUNCTION FINDI(X,A,N) !Binary chopper. Find i such that X = A(i)
Careful: it is surprisingly difficult to make this neat, due to vexations when N = 0 or 1.
Careful: it is surprisingly difficult to make this neat, due to vexations when N = 0 or 1.
REAL X,A(*) !Where is X in array A(1:N)?
REAL X,A(*) !Where is X in array A(1:N)?
Line 3,029: Line 3,029:
Curse it!
Curse it!
5 FINDI = -L !X is not found. Insert it at L + 1, i.e. at A(1 - FINDI).
5 FINDI = -L !X is not found. Insert it at L + 1, i.e. at A(1 - FINDI).
END FUNCTION FINDI !A's values need not be all different, merely in order. </lang>
END FUNCTION FINDI !A's values need not be all different, merely in order. </syntaxhighlight>
The point of this is that the IF-test is going to initiate some jumps, so why not arrange that one of the bound adjustments needs no subsequent jump to the start of the next iteration - in the first version, both bound adjustments needed such a jump, the GO TO 1 statements. This was done by shifting the code for label 2 up to precede the code for label 1 - and removing its now pointless GO TO 1 (executed each time), but adding an initial GO TO 1, executed once only. This sort of change is routine when manipulating spaghetti code...
The point of this is that the IF-test is going to initiate some jumps, so why not arrange that one of the bound adjustments needs no subsequent jump to the start of the next iteration - in the first version, both bound adjustments needed such a jump, the GO TO 1 statements. This was done by shifting the code for label 2 up to precede the code for label 1 - and removing its now pointless GO TO 1 (executed each time), but adding an initial GO TO 1, executed once only. This sort of change is routine when manipulating spaghetti code...


Line 3,050: Line 3,050:
Straightforward translation of imperative iterative algorithm.
Straightforward translation of imperative iterative algorithm.


<lang Futhark>
<syntaxhighlight lang=Futhark>
fun main(as: [n]int, value: int): int =
fun main(as: [n]int, value: int): int =
let low = 0
let low = 0
Line 3,064: Line 3,064:
else (mid, mid-1) -- Force termination.
else (mid, mid-1) -- Force termination.
in low
in low
</syntaxhighlight>
</lang>


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap>Find := function(v, x)
<syntaxhighlight lang=gap>Find := function(v, x)
local low, high, mid;
local low, high, mid;
low := 1;
low := 1;
Line 3,089: Line 3,089:
# fail
# fail
Find(u, 35);
Find(u, 35);
# 5</lang>
# 5</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
'''Recursive''':
'''Recursive''':
<lang go>func binarySearch(a []float64, value float64, low int, high int) int {
<syntaxhighlight lang=go>func binarySearch(a []float64, value float64, low int, high int) int {
if high < low {
if high < low {
return -1
return -1
Line 3,104: Line 3,104:
}
}
return mid
return mid
}</lang>
}</syntaxhighlight>
'''Iterative''':
'''Iterative''':
<lang go>func binarySearch(a []float64, value float64) int {
<syntaxhighlight lang=go>func binarySearch(a []float64, value float64) int {
low := 0
low := 0
high := len(a) - 1
high := len(a) - 1
Line 3,120: Line 3,120:
}
}
return -1
return -1
}</lang>
}</syntaxhighlight>
'''Library''':
'''Library''':
<lang go>import "sort"
<syntaxhighlight lang=go>import "sort"


//...
//...


sort.SearchInts([]int{0,1,4,5,6,7,8,9}, 6) // evaluates to 4</lang>
sort.SearchInts([]int{0,1,4,5,6,7,8,9}, 6) // evaluates to 4</syntaxhighlight>
Exploration of library source code shows that it uses the <tt>mid = low + (high - low) / 2</tt> technique to avoid overflow.
Exploration of library source code shows that it uses the <tt>mid = low + (high - low) / 2</tt> technique to avoid overflow.


Line 3,134: Line 3,134:
Both solutions use ''sublists'' and a tracking offset in preference to "high" and "low".
Both solutions use ''sublists'' and a tracking offset in preference to "high" and "low".
====Recursive Solution====
====Recursive Solution====
<lang groovy>
<syntaxhighlight lang=groovy>
def binSearchR
def binSearchR
//define binSearchR closure.
//define binSearchR closure.
Line 3,148: Line 3,148:
: [index: offset + m]
: [index: offset + m]
}
}
</syntaxhighlight>
</lang>


====Iterative Solution====
====Iterative Solution====
<lang groovy>def binSearchI = { aList, target ->
<syntaxhighlight lang=groovy>def binSearchI = { aList, target ->
def a = aList
def a = aList
def offset = 0
def offset = 0
Line 3,167: Line 3,167:
}
}
return ["insertion point": offset]
return ["insertion point": offset]
}</lang>
}</syntaxhighlight>
Test:
Test:
<lang groovy>def a = [] as Set
<syntaxhighlight lang=groovy>def a = [] as Set
def random = new Random()
def random = new Random()
while (a.size() < 20) { a << random.nextInt(30) }
while (a.size() < 20) { a << random.nextInt(30) }
Line 3,185: Line 3,185:
println """
println """
Answer: ${answers[0]}, : ${source[answers[0].values().iterator().next()]}"""
Answer: ${answers[0]}, : ${source[answers[0].values().iterator().next()]}"""
}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>[1, 2, 5, 8, 9, 10, 11, 14, 15, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 29]
<pre>[1, 2, 5, 8, 9, 10, 11, 14, 15, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 29]
Line 3,203: Line 3,203:


The algorithm itself, parametrized by an "interrogation" predicate ''p'' in the spirit of the explanation above:
The algorithm itself, parametrized by an "interrogation" predicate ''p'' in the spirit of the explanation above:
<lang haskell>import Data.Array (Array, Ix, (!), listArray, bounds)
<syntaxhighlight lang=haskell>import Data.Array (Array, Ix, (!), listArray, bounds)


-- BINARY SEARCH --------------------------------------------------------------
-- BINARY SEARCH --------------------------------------------------------------
Line 3,254: Line 3,254:
case found of
case found of
Nothing -> "' Not found"
Nothing -> "' Not found"
Just x -> "' found at index " ++ show x</lang>
Just x -> "' found at index " ++ show x</syntaxhighlight>
{{Out}}
{{Out}}
<pre>'mu' found at index 9</pre>
<pre>'mu' found at index 9</pre>
Line 3,261: Line 3,261:
A common optimisation of recursion is to delegate the main computation to a helper function with simpler type signature. For the option type of the return value, we could also use an Either as an alternative to a Maybe.
A common optimisation of recursion is to delegate the main computation to a helper function with simpler type signature. For the option type of the return value, we could also use an Either as an alternative to a Maybe.


<lang haskell>import Data.Array (Array, Ix, (!), listArray, bounds)
<syntaxhighlight lang=haskell>import Data.Array (Array, Ix, (!), listArray, bounds)


-- BINARY SEARCH USING A HELPER FUNCTION WITH A SIMPLER TYPE SIGNATURE
-- BINARY SEARCH USING A HELPER FUNCTION WITH A SIMPLER TYPE SIGNATURE
Line 3,306: Line 3,306:
("' " ++)
("' " ++)
(("' found at index " ++) . show)
(("' found at index " ++) . show)
(findIndexBinary (compare needle) haystack)</lang>
(findIndexBinary (compare needle) haystack)</syntaxhighlight>
{{Out}}
{{Out}}
<pre>'lambda' found at index 8</pre>
<pre>'lambda' found at index 8</pre>
Line 3,316: Line 3,316:
It returns the result of applying '''f''' until '''p''' holds.
It returns the result of applying '''f''' until '''p''' holds.


<lang haskell>import Data.Array (Array, Ix, (!), listArray, bounds)
<syntaxhighlight lang=haskell>import Data.Array (Array, Ix, (!), listArray, bounds)


-- BINARY SEARCH USING THE ITERATIVE ALGORITHM
-- BINARY SEARCH USING THE ITERATIVE ALGORITHM
Line 3,365: Line 3,365:
("' " ++)
("' " ++)
(("' found at index " ++) . show)
(("' found at index " ++) . show)
(findIndexBinary_ (compare needle) haystack)</lang>
(findIndexBinary_ (compare needle) haystack)</syntaxhighlight>
{{Out}}
{{Out}}
<pre>'kappa' found at index 7</pre>
<pre>'kappa' found at index 7</pre>


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang hicest>REAL :: n=10, array(n)
<syntaxhighlight lang=hicest>REAL :: n=10, array(n)


array = NINT( RAN(n) )
array = NINT( RAN(n) )
Line 3,401: Line 3,401:
ENDIF
ENDIF
ENDDO
ENDDO
END</lang>
END</syntaxhighlight>
<lang hicest>7 has position 9 in 0 0 1 2 3 3 4 6 7 8
<syntaxhighlight lang=hicest>7 has position 9 in 0 0 1 2 3 3 4 6 7 8
5 has position 0 in 0 0 1 2 3 3 4 6 7 8</lang>
5 has position 0 in 0 0 1 2 3 3 4 6 7 8</syntaxhighlight>


=={{header|Hoon}}==
=={{header|Hoon}}==
<lang hoon>|= [arr=(list @ud) x=@ud]
<syntaxhighlight lang=hoon>|= [arr=(list @ud) x=@ud]
=/ lo=@ud 0
=/ lo=@ud 0
=/ hi=@ud (dec (lent arr))
=/ hi=@ud (dec (lent arr))
Line 3,415: Line 3,415:
?: (lth x val) $(hi (dec mid))
?: (lth x val) $(hi (dec mid))
?: (gth x val) $(lo +(mid))
?: (gth x val) $(lo +(mid))
mid</lang>
mid</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Only a recursive solution is shown here.
Only a recursive solution is shown here.
<lang icon>procedure binsearch(A, target)
<syntaxhighlight lang=icon>procedure binsearch(A, target)
if *A = 0 then fail
if *A = 0 then fail
mid := *A/2 + 1
mid := *A/2 + 1
Line 3,429: Line 3,429:
}
}
return mid
return mid
end</lang>
end</syntaxhighlight>
A program to test this is:
A program to test this is:
<lang icon>procedure main(args)
<syntaxhighlight lang=icon>procedure main(args)
target := integer(!args) | 3
target := integer(!args) | 3
every put(A := [], 1 to 18 by 2)
every put(A := [], 1 to 18 by 2)
Line 3,443: Line 3,443:
every writes(!A," ")
every writes(!A," ")
write()
write()
end</lang>
end</syntaxhighlight>
with some sample runs:
with some sample runs:
<pre>
<pre>
Line 3,478: Line 3,478:
=={{header|J}}==
=={{header|J}}==
J already includes a binary search primitive (<code>I.</code>). The following code offers an interface compatible with the requirement of this task, and returns either the index of the element if it has been found or 'Not Found' otherwise:
J already includes a binary search primitive (<code>I.</code>). The following code offers an interface compatible with the requirement of this task, and returns either the index of the element if it has been found or 'Not Found' otherwise:
<lang j>bs=. i. 'Not Found'"_^:(-.@-:) I.</lang>
<syntaxhighlight lang=j>bs=. i. 'Not Found'"_^:(-.@-:) I.</syntaxhighlight>
'''Examples:'''
'''Examples:'''
<lang j> 2 3 5 6 8 10 11 15 19 20 bs 11
<syntaxhighlight lang=j> 2 3 5 6 8 10 11 15 19 20 bs 11
6
6
2 3 5 6 8 10 11 15 19 20 bs 12
2 3 5 6 8 10 11 15 19 20 bs 12
Not Found</lang>
Not Found</syntaxhighlight>
Direct tacit iterative and recursive versions to compare to other implementations follow:
Direct tacit iterative and recursive versions to compare to other implementations follow:


'''Iterative'''
'''Iterative'''
<lang j>'X Y L H M'=. i.5 NB. Setting mnemonics for boxes
<syntaxhighlight lang=j>'X Y L H M'=. i.5 NB. Setting mnemonics for boxes
f=. &({::) NB. Fetching the contents of a box
f=. &({::) NB. Fetching the contents of a box
o=. @: NB. Composing verbs (functions)
o=. @: NB. Composing verbs (functions)
Line 3,499: Line 3,499:
return=. (M f) o ((<@:('Not Found'"_) M} ]) ^: (_ ~: L f))
return=. (M f) o ((<@:('Not Found'"_) M} ]) ^: (_ ~: L f))


bs=. return o (squeeze o midpoint ^: (L f <: H f) ^:_) o LowHigh o boxes</lang>
bs=. return o (squeeze o midpoint ^: (L f <: H f) ^:_) o LowHigh o boxes</syntaxhighlight>
'''Recursive'''
'''Recursive'''
<lang j>'X Y L H M'=. i.5 NB. Setting mnemonics for boxes
<syntaxhighlight lang=j>'X Y L H M'=. i.5 NB. Setting mnemonics for boxes
f=. &({::) NB. Fetching the contents of a box
f=. &({::) NB. Fetching the contents of a box
o=. @: NB. Composing verbs (functions)
o=. @: NB. Composing verbs (functions)
Line 3,511: Line 3,511:
recur=. (X f bs Y f ; L f ; (_1 + M f))`(M f)`(X f bs Y f ; (1 + M f) ; H f)@.case
recur=. (X f bs Y f ; L f ; (_1 + M f))`(M f)`(X f bs Y f ; (1 + M f) ; H f)@.case


bs=. (recur o midpoint`('Not Found'"_) @. (H f < L f) o boxes) :: ([ bs ] ; 0 ; (<: o # o [))</lang>
bs=. (recur o midpoint`('Not Found'"_) @. (H f < L f) o boxes) :: ([ bs ] ; 0 ; (<: o # o [))</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
'''Iterative'''
'''Iterative'''
<lang java>public class BinarySearchIterative {
<syntaxhighlight lang=java>public class BinarySearchIterative {


public static int binarySearch(int[] nums, int check) {
public static int binarySearch(int[] nums, int check) {
Line 3,543: Line 3,543:
}
}
}
}
}</lang>
}</syntaxhighlight>


'''Recursive'''
'''Recursive'''


<lang java>public class BinarySearchRecursive {
<syntaxhighlight lang=java>public class BinarySearchRecursive {


public static int binarySearch(int[] haystack, int needle, int lo, int hi) {
public static int binarySearch(int[] haystack, int needle, int lo, int hi) {
Line 3,574: Line 3,574:
}
}
}
}
}</lang>
}</syntaxhighlight>
'''Library'''
'''Library'''
When the key is not found, the following functions return <code>~insertionPoint</code> (the bitwise complement of the index where the key would be inserted, which is guaranteed to be a negative number).
When the key is not found, the following functions return <code>~insertionPoint</code> (the bitwise complement of the index where the key would be inserted, which is guaranteed to be a negative number).


For arrays:
For arrays:
<lang java>import java.util.Arrays;
<syntaxhighlight lang=java>import java.util.Arrays;


int index = Arrays.binarySearch(array, thing);
int index = Arrays.binarySearch(array, thing);
Line 3,586: Line 3,586:
// for objects, also optionally accepts an additional comparator argument:
// for objects, also optionally accepts an additional comparator argument:
int index = Arrays.binarySearch(array, thing, comparator);
int index = Arrays.binarySearch(array, thing, comparator);
int index = Arrays.binarySearch(array, startIndex, endIndex, thing, comparator);</lang>
int index = Arrays.binarySearch(array, startIndex, endIndex, thing, comparator);</syntaxhighlight>
For Lists:
For Lists:
<lang java>import java.util.Collections;
<syntaxhighlight lang=java>import java.util.Collections;


int index = Collections.binarySearch(list, thing);
int index = Collections.binarySearch(list, thing);
int index = Collections.binarySearch(list, thing, comparator);</lang>
int index = Collections.binarySearch(list, thing, comparator);</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
===ES5===
===ES5===
Recursive binary search implementation
Recursive binary search implementation
<lang javascript>function binary_search_recursive(a, value, lo, hi) {
<syntaxhighlight lang=javascript>function binary_search_recursive(a, value, lo, hi) {
if (hi < lo) { return null; }
if (hi < lo) { return null; }


Line 3,608: Line 3,608:
}
}
return mid;
return mid;
}</lang>
}</syntaxhighlight>
Iterative binary search implementation
Iterative binary search implementation
<lang javascript>function binary_search_iterative(a, value) {
<syntaxhighlight lang=javascript>function binary_search_iterative(a, value) {
var mid, lo = 0,
var mid, lo = 0,
hi = a.length - 1;
hi = a.length - 1;
Line 3,626: Line 3,626:
}
}
return null;
return null;
}</lang>
}</syntaxhighlight>


===ES6===
===ES6===
Line 3,632: Line 3,632:
Recursive and iterative, by composition of pure functions, with tests and output:
Recursive and iterative, by composition of pure functions, with tests and output:


<lang javascript>(() => {
<syntaxhighlight lang=javascript>(() => {
'use strict';
'use strict';


Line 3,788: Line 3,788:
// MAIN ---
// MAIN ---
return main();
return main();
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<pre>[
<pre>[
Line 3,833: Line 3,833:
If the input array is sorted, then binarySearch(value) as defined here will return an index (i.e. offset) of value in the array if the array contains the value, and otherwise (-1 - ix), where ix is the insertion point, if the value cannot be found. binarySearch will always terminate.
If the input array is sorted, then binarySearch(value) as defined here will return an index (i.e. offset) of value in the array if the array contains the value, and otherwise (-1 - ix), where ix is the insertion point, if the value cannot be found. binarySearch will always terminate.


Recursive solution:<lang jq>def binarySearch(value):
Recursive solution:<syntaxhighlight lang=jq>def binarySearch(value):
# To avoid copying the array, simply pass in the current low and high offsets
# To avoid copying the array, simply pass in the current low and high offsets
def binarySearch(low; high):
def binarySearch(low; high):
Line 3,843: Line 3,843:
end
end
end;
end;
binarySearch(0; length-1);</lang>
binarySearch(0; length-1);</syntaxhighlight>
Example:<lang jq>[-1,-1.1,1,1,null,[null]] | binarySearch(1)</lang>
Example:<syntaxhighlight lang=jq>[-1,-1.1,1,1,null,[null]] | binarySearch(1)</syntaxhighlight>
{{Out}}
{{Out}}
2
2


=={{header|Jsish}}==
=={{header|Jsish}}==
<lang javascript>/**
<syntaxhighlight lang=javascript>/**
Binary search, in Jsish, based on Javascript entry
Binary search, in Jsish, based on Javascript entry
Tectonics: jsish -u -time true -verbose true binarySearch.jsi
Tectonics: jsish -u -time true -verbose true binarySearch.jsi
Line 3,901: Line 3,901:
puts('Iterative:', Util.times(function() { binarySearchIterative(arr, 42); }, 100), 'µs');
puts('Iterative:', Util.times(function() { binarySearchIterative(arr, 42); }, 100), 'µs');
puts('Recursive:', Util.times(function() { binarySearchRecursive(arr, 42, 0, arr.length - 1); }, 100), 'µs');
puts('Recursive:', Util.times(function() { binarySearchRecursive(arr, 42, 0, arr.length - 1); }, 100), 'µs');
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,916: Line 3,916:
{{works with|Julia|0.6}}
{{works with|Julia|0.6}}
'''Iterative''':
'''Iterative''':
<lang julia>function binarysearch(lst::Vector{T}, val::T) where T
<syntaxhighlight lang=julia>function binarysearch(lst::Vector{T}, val::T) where T
low = 1
low = 1
high = length(lst)
high = length(lst)
Line 3,930: Line 3,930:
end
end
return 0
return 0
end</lang>
end</syntaxhighlight>


'''Recursive''':
'''Recursive''':
<lang julia>function binarysearch(lst::Vector{T}, value::T, low=1, high=length(lst)) where T
<syntaxhighlight lang=julia>function binarysearch(lst::Vector{T}, value::T, low=1, high=length(lst)) where T
if isempty(lst) return 0 end
if isempty(lst) return 0 end
if low ≥ high
if low ≥ high
Line 3,950: Line 3,950:
return mid
return mid
end
end
end</lang>
end</syntaxhighlight>


=={{header|K}}==
=={{header|K}}==
Recursive:
Recursive:
<syntaxhighlight lang=K>
<lang K>
bs:{[a;t]
bs:{[a;t]
if[0=#a; :_n];
if[0=#a; :_n];
Line 3,969: Line 3,969:
{bs[v;x]}' v
{bs[v;x]}' v
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
</syntaxhighlight>
</lang>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>fun <T : Comparable<T>> Array<T>.iterativeBinarySearch(target: T): Int {
<syntaxhighlight lang=scala>fun <T : Comparable<T>> Array<T>.iterativeBinarySearch(target: T): Int {
var hi = size - 1
var hi = size - 1
var lo = 0
var lo = 0
Line 4,009: Line 4,009:
r = a.recursiveBinarySearch(target, 0, a.size)
r = a.recursiveBinarySearch(target, 0, a.size)
println(if (r < 0) "$target not found" else "$target found at index $r")
println(if (r < 0) "$target not found" else "$target found at index $r")
}</lang>
}</syntaxhighlight>
{{Out}}
{{Out}}
<pre>6 found at index 4
<pre>6 found at index 4
Line 4,018: Line 4,018:
=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
Can be tested in (http://lambdaway.free.fr)[http://lambdaway.free.fr/lambdaway/?view=binary_search]
Can be tested in (http://lambdaway.free.fr)[http://lambdaway.free.fr/lambdaway/?view=binary_search]
<lang scheme>
<syntaxhighlight lang=scheme>
{def BS
{def BS
{def BS.r {lambda {:a :v :i0 :i1}
{def BS.r {lambda {:a :v :i0 :i1}
Line 4,047: Line 4,047:
{BS {B} 100} -> 100 is not found
{BS {B} 100} -> 100 is not found
{BS {B} 12345} -> 12345 is at array[6172]
{BS {B} 12345} -> 12345 is at array[6172]
</syntaxhighlight>
</lang>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<syntaxhighlight lang=lb>
<lang lb>
dim theArray(100)
dim theArray(100)
for i = 1 to 100
for i = 1 to 100
Line 4,070: Line 4,070:
END IF
END IF
END FUNCTION
END FUNCTION
</syntaxhighlight>
</lang>


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>to bsearch :value :a :lower :upper
<syntaxhighlight lang=logo>to bsearch :value :a :lower :upper
if :upper < :lower [output []]
if :upper < :lower [output []]
localmake "mid int (:lower + :upper) / 2
localmake "mid int (:lower + :upper) / 2
Line 4,079: Line 4,079:
if item :mid :a < :value [output bsearch :value :a :mid+1 :upper]
if item :mid :a < :value [output bsearch :value :a :mid+1 :upper]
output :mid
output :mid
end</lang>
end</syntaxhighlight>


=={{header|Lolcode}}==
=={{header|Lolcode}}==
'''Iterative'''
'''Iterative'''
<lang lolcode>
<syntaxhighlight lang=lolcode>
HAI 1.2
HAI 1.2
CAN HAS STDIO?
CAN HAS STDIO?
Line 4,171: Line 4,171:
KTHXBYE
KTHXBYE
end</lang>
end</syntaxhighlight>
Output
Output
<pre>
<pre>
Line 4,186: Line 4,186:
=={{header|Lua}}==
=={{header|Lua}}==
'''Iterative'''
'''Iterative'''
<lang lua>function binarySearch (list,value)
<syntaxhighlight lang=lua>function binarySearch (list,value)
local low = 1
local low = 1
local high = #list
local high = #list
Line 4,197: Line 4,197:
end
end
return false
return false
end</lang>
end</syntaxhighlight>
'''Recursive'''
'''Recursive'''
<lang lua>function binarySearch (list, value)
<syntaxhighlight lang=lua>function binarySearch (list, value)
local function search(low, high)
local function search(low, high)
if low > high then return false end
if low > high then return false end
Line 4,208: Line 4,208:
end
end
return search(1,#list)
return search(1,#list)
end</lang>
end</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
<lang M2000 Interpreter>
<syntaxhighlight lang=M2000 Interpreter>
\\ binary search
\\ binary search
const N=10
const N=10
Line 4,257: Line 4,257:
Print A()
Print A()


</syntaxhighlight>
</lang>


=={{header|M4}}==
=={{header|M4}}==
<lang M4>define(`notfound',`-1')dnl
<syntaxhighlight lang=M4>define(`notfound',`-1')dnl
define(`midsearch',`ifelse(defn($1[$4]),$2,$4,
define(`midsearch',`ifelse(defn($1[$4]),$2,$4,
`ifelse(eval(defn($1[$4])>$2),1,`binarysearch($1,$2,$3,decr($4))',`binarysearch($1,$2,incr($4),$5)')')')dnl
`ifelse(eval(defn($1[$4])>$2),1,`binarysearch($1,$2,$3,decr($4))',`binarysearch($1,$2,incr($4),$5)')')')dnl
Line 4,269: Line 4,269:
dnl
dnl
binarysearch(`a',5,1,asize)
binarysearch(`a',5,1,asize)
binarysearch(`a',8,1,asize)</lang>
binarysearch(`a',8,1,asize)</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 4,280: Line 4,280:


'''Recursive'''
'''Recursive'''
<lang Maple>BinarySearch := proc( A, value, low, high )
<syntaxhighlight lang=Maple>BinarySearch := proc( A, value, low, high )
description "recursive binary search";
description "recursive binary search";
if high < low then
if high < low then
Line 4,294: Line 4,294:
end if
end if
end if
end if
end proc:</lang>
end proc:</syntaxhighlight>


'''Iterative'''
'''Iterative'''
<lang Maple>BinarySearch := proc( A, value )
<syntaxhighlight lang=Maple>BinarySearch := proc( A, value )
description "iterative binary search";
description "iterative binary search";
local low, high;
local low, high;
Line 4,313: Line 4,313:
end do;
end do;
FAIL
FAIL
end proc:</lang>
end proc:</syntaxhighlight>
We can use either lists or Arrays (or Vectors) for the first argument for these.
We can use either lists or Arrays (or Vectors) for the first argument for these.
<lang Maple>> N := 10:
<syntaxhighlight lang=Maple>> N := 10:
> P := [seq]( ithprime( i ), i = 1 .. N ):
> P := [seq]( ithprime( i ), i = 1 .. N ):
> BinarySearch( P, 12, 1, N ); # recursive version
> BinarySearch( P, 12, 1, N ); # recursive version
Line 4,331: Line 4,331:


> PP[ 3 ];
> PP[ 3 ];
13</lang>
13</syntaxhighlight>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
'''Recursive'''
'''Recursive'''
<lang Mathematica>BinarySearchRecursive[x_List, val_, lo_, hi_] :=
<syntaxhighlight lang=Mathematica>BinarySearchRecursive[x_List, val_, lo_, hi_] :=
Module[{mid = lo + Round@((hi - lo)/2)},
Module[{mid = lo + Round@((hi - lo)/2)},
If[hi < lo, Return[-1]];
If[hi < lo, Return[-1]];
Line 4,343: Line 4,343:
True, mid]
True, mid]
];
];
]</lang>
]</syntaxhighlight>
'''Iterative'''
'''Iterative'''
<lang Mathematica>BinarySearch[x_List, val_] := Module[{lo = 1, hi = Length@x, mid},
<syntaxhighlight lang=Mathematica>BinarySearch[x_List, val_] := Module[{lo = 1, hi = Length@x, mid},
While[lo <= hi,
While[lo <= hi,
mid = lo + Round@((hi - lo)/2);
mid = lo + Round@((hi - lo)/2);
Line 4,354: Line 4,354:
];
];
Return[-1];
Return[-1];
]</lang>
]</syntaxhighlight>


=={{header|MATLAB}}==
=={{header|MATLAB}}==
'''Recursive'''
'''Recursive'''
<lang MATLAB>function mid = binarySearchRec(list,value,low,high)
<syntaxhighlight lang=MATLAB>function mid = binarySearchRec(list,value,low,high)


if( high < low )
if( high < low )
Line 4,377: Line 4,377:
end
end
end</lang>
end</syntaxhighlight>
Sample Usage:
Sample Usage:
<lang MATLAB>>> binarySearchRec([1 2 3 4 5 6 6.5 7 8 9 11 18],6.5,1,numel([1 2 3 4 5 6 6.5 7 8 9 11 18]))
<syntaxhighlight lang=MATLAB>>> binarySearchRec([1 2 3 4 5 6 6.5 7 8 9 11 18],6.5,1,numel([1 2 3 4 5 6 6.5 7 8 9 11 18]))


ans =
ans =


7</lang>
7</syntaxhighlight>
'''Iterative'''
'''Iterative'''
<lang MATLAB>function mid = binarySearchIter(list,value)
<syntaxhighlight lang=MATLAB>function mid = binarySearchIter(list,value)


low = 1;
low = 1;
Line 4,404: Line 4,404:
mid = [];
mid = [];
end</lang>
end</syntaxhighlight>
Sample Usage:
Sample Usage:
<lang MATLAB>>> binarySearchIter([1 2 3 4 5 6 6.5 7 8 9 11 18],6.5)
<syntaxhighlight lang=MATLAB>>> binarySearchIter([1 2 3 4 5 6 6.5 7 8 9 11 18],6.5)


ans =
ans =


7</lang>
7</syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>find(L, n) := block([i: 1, j: length(L), k, p],
<syntaxhighlight lang=maxima>find(L, n) := block([i: 1, j: length(L), k, p],
if n < L[i] or n > L[j] then 0 else (
if n < L[i] or n > L[j] then 0 else (
while j - i > 0 do (
while j - i > 0 do (
Line 4,432: Line 4,432:
0
0
find(a, 421);
find(a, 421);
82</lang>
82</syntaxhighlight>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
'''Iterative'''
'''Iterative'''
<lang maxscript>fn binarySearchIterative arr value =
<syntaxhighlight lang=maxscript>fn binarySearchIterative arr value =
(
(
lower = 1
lower = 1
Line 4,460: Line 4,460:


arr = #(1, 3, 4, 5, 6, 7, 8, 9, 10)
arr = #(1, 3, 4, 5, 6, 7, 8, 9, 10)
result = binarySearchIterative arr 6</lang>
result = binarySearchIterative arr 6</syntaxhighlight>
'''Recursive'''
'''Recursive'''
<lang maxscript>fn binarySearchRecursive arr value lower upper =
<syntaxhighlight lang=maxscript>fn binarySearchRecursive arr value lower upper =
(
(
if lower == upper then
if lower == upper then
Line 4,491: Line 4,491:


arr = #(1, 3, 4, 5, 6, 7, 8, 9, 10)
arr = #(1, 3, 4, 5, 6, 7, 8, 9, 10)
result = binarySearchRecursive arr 6 1 arr.count</lang>
result = binarySearchRecursive arr 6 1 arr.count</syntaxhighlight>


=={{header|MiniScript}}==
=={{header|MiniScript}}==
'''Recursive:'''
'''Recursive:'''
<lang MiniScript>binarySearch = function(A, value, low, high)
<syntaxhighlight lang=MiniScript>binarySearch = function(A, value, low, high)
if high < low then return null
if high < low then return null
mid = floor((low + high) / 2)
mid = floor((low + high) / 2)
Line 4,501: Line 4,501:
if A[mid] < value then return binarySearch(A, value, mid+1, high)
if A[mid] < value then return binarySearch(A, value, mid+1, high)
return mid
return mid
end function</lang>
end function</syntaxhighlight>


'''Iterative:'''
'''Iterative:'''
<lang MiniScript>binarySearch = function(A, value)
<syntaxhighlight lang=MiniScript>binarySearch = function(A, value)
low = 0
low = 0
high = A.len - 1
high = A.len - 1
Line 4,518: Line 4,518:
end if
end if
end while
end while
end function</lang>
end function</syntaxhighlight>


=={{header|N/t/roff}}==
=={{header|N/t/roff}}==


{{works with|GNU TROFF|1.22.2}}
{{works with|GNU TROFF|1.22.2}}
<lang>.de end
<syntaxhighlight lang=text>.de end
..
..
.de array
.de array
Line 4,561: Line 4,561:
.ie \n[guess]=0 The item \fBdoesn't exist\fP.
.ie \n[guess]=0 The item \fBdoesn't exist\fP.
.el The item \fBdoes exist\fP.
.el The item \fBdoes exist\fP.
</syntaxhighlight>
</lang>


=={{header|Nim}}==
=={{header|Nim}}==
'''Library'''
'''Library'''
<lang nim>import algorithm
<syntaxhighlight lang=nim>import algorithm


let s = @[2,3,4,5,6,7,8,9,10,12,14,16,18,20,22,25,27,30]
let s = @[2,3,4,5,6,7,8,9,10,12,14,16,18,20,22,25,27,30]
echo binarySearch(s, 10)</lang>
echo binarySearch(s, 10)</syntaxhighlight>


'''Iterative''' (from the standard library)
'''Iterative''' (from the standard library)
<lang nim>proc binarySearch[T](a: openArray[T], key: T): int =
<syntaxhighlight lang=nim>proc binarySearch[T](a: openArray[T], key: T): int =
var b = len(a)
var b = len(a)
while result < b:
while result < b:
Line 4,577: Line 4,577:
if a[mid] < key: result = mid + 1
if a[mid] < key: result = mid + 1
else: b = mid
else: b = mid
if result >= len(a) or a[result] != key: result = -1</lang>
if result >= len(a) or a[result] != key: result = -1</syntaxhighlight>


=={{header|Niue}}==
=={{header|Niue}}==
'''Library'''
'''Library'''
<lang ocaml>1 2 3 4 5
<syntaxhighlight lang=ocaml>1 2 3 4 5
3 bsearch . ( => 2 )
3 bsearch . ( => 2 )
5 bsearch . ( => 0 )
5 bsearch . ( => 0 )
Line 4,590: Line 4,590:
'tom bsearch . ( => 0 )
'tom bsearch . ( => 0 )
'kenny bsearch . ( => 2 )
'kenny bsearch . ( => 2 )
'tony bsearch . ( => -1)</lang>
'tony bsearch . ( => -1)</syntaxhighlight>


=={{header|Objeck}}==
=={{header|Objeck}}==
'''Iterative'''
'''Iterative'''
<lang objeck>use Structure;
<syntaxhighlight lang=objeck>use Structure;


bundle Default {
bundle Default {
Line 4,625: Line 4,625:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Objective-C}}==
=={{header|Objective-C}}==
'''Iterative'''
'''Iterative'''
<lang objc>#import <Foundation/Foundation.h>
<syntaxhighlight lang=objc>#import <Foundation/Foundation.h>


@interface NSArray (BinarySearch)
@interface NSArray (BinarySearch)
Line 4,669: Line 4,669:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>
'''Recursive'''
'''Recursive'''
<lang objc>#import <Foundation/Foundation.h>
<syntaxhighlight lang=objc>#import <Foundation/Foundation.h>


@interface NSArray (BinarySearchRecursive)
@interface NSArray (BinarySearchRecursive)
Line 4,708: Line 4,708:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>
'''Library'''
'''Library'''
{{works with|Mac OS X|10.6+}}
{{works with|Mac OS X|10.6+}}
<lang objc>#import <Foundation/Foundation.h>
<syntaxhighlight lang=objc>#import <Foundation/Foundation.h>


int main()
int main()
Line 4,725: Line 4,725:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>
Using Core Foundation (part of Cocoa, all versions):
Using Core Foundation (part of Cocoa, all versions):
<lang objc>#import <Foundation/Foundation.h>
<syntaxhighlight lang=objc>#import <Foundation/Foundation.h>


CFComparisonResult myComparator(const void *x, const void *y, void *context) {
CFComparisonResult myComparator(const void *x, const void *y, void *context) {
Line 4,745: Line 4,745:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
'''Recursive'''
'''Recursive'''
<lang ocaml>let rec binary_search a value low high =
<syntaxhighlight lang=ocaml>let rec binary_search a value low high =
if high = low then
if high = low then
if a.(low) = value then
if a.(low) = value then
Line 4,761: Line 4,761:
binary_search a value (mid + 1) high
binary_search a value (mid + 1) high
else
else
mid</lang>
mid</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 4,775: Line 4,775:
=={{header|Octave}}==
=={{header|Octave}}==
'''Recursive'''
'''Recursive'''
<lang octave>function i = binsearch_r(array, val, low, high)
<syntaxhighlight lang=octave>function i = binsearch_r(array, val, low, high)
if ( high < low )
if ( high < low )
i = 0;
i = 0;
Line 4,788: Line 4,788:
endif
endif
endif
endif
endfunction</lang>
endfunction</syntaxhighlight>
'''Iterative'''
'''Iterative'''
<lang octave>function i = binsearch(array, value)
<syntaxhighlight lang=octave>function i = binsearch(array, value)
low = 1;
low = 1;
high = numel(array);
high = numel(array);
Line 4,805: Line 4,805:
endif
endif
endwhile
endwhile
endfunction</lang>
endfunction</syntaxhighlight>
'''Example of using'''
'''Example of using'''
<lang octave>r = sort(discrete_rnd(10, [1:10], ones(10,1)/10));
<syntaxhighlight lang=octave>r = sort(discrete_rnd(10, [1:10], ones(10,1)/10));
disp(r);
disp(r);
binsearch_r(r, 5, 1, numel(r))
binsearch_r(r, 5, 1, numel(r))
binsearch(r, 5)</lang>
binsearch(r, 5)</syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
<lang scheme>
<syntaxhighlight lang=scheme>
(define (binary-search value vector)
(define (binary-search value vector)
(let helper ((low 0)
(let helper ((low 0)
Line 4,829: Line 4,829:
(binary-search 12 [1 2 3 4 5 6 7 8 9 10 11 12 13]))
(binary-search 12 [1 2 3 4 5 6 7 8 9 10 11 12 13]))
; ==> 12
; ==> 12
</syntaxhighlight>
</lang>


=={{header|ooRexx}}==
=={{header|ooRexx}}==
<lang ooRexx>
<syntaxhighlight lang=ooRexx>
data = .array~of(1, 3, 5, 7, 9, 11)
data = .array~of(1, 3, 5, 7, 9, 11)
-- search keys with a number of edge cases
-- search keys with a number of edge cases
Line 4,885: Line 4,885:
end
end
return 0
return 0
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 4,907: Line 4,907:
=={{header|Oz}}==
=={{header|Oz}}==
'''Recursive'''
'''Recursive'''
<lang oz>declare
<syntaxhighlight lang=oz>declare
fun {BinarySearch Arr Val}
fun {BinarySearch Arr Val}
fun {Search Low High}
fun {Search Low High}
Line 4,927: Line 4,927:
in
in
{System.printInfo "searching 4: "} {Show {BinarySearch A 4}}
{System.printInfo "searching 4: "} {Show {BinarySearch A 4}}
{System.printInfo "searching 8: "} {Show {BinarySearch A 8}}</lang>
{System.printInfo "searching 8: "} {Show {BinarySearch A 8}}</syntaxhighlight>
'''Iterative'''
'''Iterative'''
<lang oz>declare
<syntaxhighlight lang=oz>declare
fun {BinarySearch Arr Val}
fun {BinarySearch Arr Val}
Low = {NewCell {Array.low Arr}}
Low = {NewCell {Array.low Arr}}
Line 4,947: Line 4,947:
in
in
{System.printInfo "searching 4: "} {Show {BinarySearch A 4}}
{System.printInfo "searching 4: "} {Show {BinarySearch A 4}}
{System.printInfo "searching 8: "} {Show {BinarySearch A 8}}</lang>
{System.printInfo "searching 8: "} {Show {BinarySearch A 8}}</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
Note that, despite the name, <code>setsearch</code> works on sorted vectors as well as sets.
Note that, despite the name, <code>setsearch</code> works on sorted vectors as well as sets.
<lang parigp>setsearch(s, n)</lang>
<syntaxhighlight lang=parigp>setsearch(s, n)</syntaxhighlight>


The following is another implementation that takes a more manual approach. Instead of using an intrinsic function, a general binary search algorithm is implemented using the language alone.
The following is another implementation that takes a more manual approach. Instead of using an intrinsic function, a general binary search algorithm is implemented using the language alone.
Line 4,957: Line 4,957:
{{trans|N/t/roff}}
{{trans|N/t/roff}}


<lang parigp>binarysearch(v, x) = {
<syntaxhighlight lang=parigp>binarysearch(v, x) = {
local(
local(
minm = 1,
minm = 1,
Line 4,980: Line 4,980:
print("Item exists on index ", idx), \
print("Item exists on index ", idx), \
print("Item does not exist anywhere.") \
print("Item does not exist anywhere.") \
)</lang>
)</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
'''Iterative'''
'''Iterative'''
<lang pascal>function binary_search(element: real; list: array of real): integer;
<syntaxhighlight lang=pascal>function binary_search(element: real; list: array of real): integer;
var
var
l, m, h: integer;
l, m, h: integer;
Line 5,008: Line 5,008:
end;
end;
end;
end;
end;</lang>
end;</syntaxhighlight>
Usage:
Usage:
<lang pascal>var
<syntaxhighlight lang=pascal>var
list: array[0 .. 9] of real;
list: array[0 .. 9] of real;
// ...
// ...
indexof := binary_search(123, list);</lang>
indexof := binary_search(123, list);</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
'''Iterative'''
'''Iterative'''
<lang perl>sub binary_search {
<syntaxhighlight lang=perl>sub binary_search {
my ($array_ref, $value, $left, $right) = @_;
my ($array_ref, $value, $left, $right) = @_;
while ($left <= $right) {
while ($left <= $right) {
Line 5,032: Line 5,032:
}
}
return -1;
return -1;
}</lang>
}</syntaxhighlight>
'''Recursive'''
'''Recursive'''
<lang perl>sub binary_search {
<syntaxhighlight lang=perl>sub binary_search {
my ($array_ref, $value, $left, $right) = @_;
my ($array_ref, $value, $left, $right) = @_;
return -1 if ($right < $left);
return -1 if ($right < $left);
Line 5,047: Line 5,047:
binary_search($array_ref, $value, $middle + 1, $right);
binary_search($array_ref, $value, $middle + 1, $right);
}
}
}</lang>
}</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
Standard autoinclude builtin/bsearch.e, reproduced here (for reference only, don't copy/paste unless you plan to modify and rename it)
Standard autoinclude builtin/bsearch.e, reproduced here (for reference only, don't copy/paste unless you plan to modify and rename it)
<!--<lang Phix>-->
<!--<syntaxhighlight lang=Phix>-->
<span style="color: #008080;">global</span> <span style="color: #008080;">function</span> <span style="color: #7060A8;">binary_search</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">needle</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">haystack</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">global</span> <span style="color: #008080;">function</span> <span style="color: #7060A8;">binary_search</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">needle</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">haystack</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">lo</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">lo</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span>
Line 5,072: Line 5,072:
<span style="color: #008080;">return</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">mid</span> <span style="color: #000080;font-style:italic;">-- where it would go, if inserted now</span>
<span style="color: #008080;">return</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">mid</span> <span style="color: #000080;font-style:italic;">-- where it would go, if inserted now</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
The low + (high-low)/2 trick is not needed, since interim integer results are accurate to 53 bits (on 32 bit, 64 bits on 64 bit) on Phix.
The low + (high-low)/2 trick is not needed, since interim integer results are accurate to 53 bits (on 32 bit, 64 bits on 64 bit) on Phix.


Returns a positive index if found, otherwise the negative index where it would go if inserted now. Example use
Returns a positive index if found, otherwise the negative index where it would go if inserted now. Example use
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang=Phix>(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">binary_search</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">})</span> <span style="color: #000080;font-style:italic;">-- -1</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">binary_search</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">})</span> <span style="color: #000080;font-style:italic;">-- -1</span>
Line 5,085: Line 5,085:
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">binary_search</span><span style="color: #0000FF;">(</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">})</span> <span style="color: #000080;font-style:italic;">-- 3</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">binary_search</span><span style="color: #0000FF;">(</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">})</span> <span style="color: #000080;font-style:italic;">-- 3</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">binary_search</span><span style="color: #0000FF;">(</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">})</span> <span style="color: #000080;font-style:italic;">-- -4</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">binary_search</span><span style="color: #0000FF;">(</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">})</span> <span style="color: #000080;font-style:italic;">-- -4</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|PHP}}==
=={{header|PHP}}==
'''Iterative'''
'''Iterative'''
<lang php>function binary_search( $array, $secret, $start, $end )
<syntaxhighlight lang=php>function binary_search( $array, $secret, $start, $end )
{
{
do
do
Line 5,107: Line 5,107:


return $guess;
return $guess;
}</lang>
}</syntaxhighlight>
'''Recursive'''
'''Recursive'''
<lang php>function binary_search( $array, $secret, $start, $end )
<syntaxhighlight lang=php>function binary_search( $array, $secret, $start, $end )
{
{
$guess = (int)($start + ( ( $end - $start ) / 2 ));
$guess = (int)($start + ( ( $end - $start ) / 2 ));
Line 5,123: Line 5,123:


return $guess;
return $guess;
}</lang>
}</syntaxhighlight>


=={{header|Picat}}==
=={{header|Picat}}==
===Iterative===
===Iterative===
<lang Picat>go =>
<syntaxhighlight lang=Picat>go =>
A = [2, 4, 6, 8, 9],
A = [2, 4, 6, 8, 9],
TestValues = [2,1,8,10,9,5],
TestValues = [2,1,8,10,9,5],
Line 5,172: Line 5,172:
end,
end,
V = V1.
V = V1.
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 5,185: Line 5,185:


===Recursive version===
===Recursive version===
<lang Picat>binary_search_rec(A, Value) = Ret =>
<syntaxhighlight lang=Picat>binary_search_rec(A, Value) = Ret =>
Ret = binary_search_rec(A,Value, 1, A.length).
Ret = binary_search_rec(A,Value, 1, A.length).


Line 5,197: Line 5,197:
Mid1 := binary_search_rec(A, Value, Mid1+1, High)
Mid1 := binary_search_rec(A, Value, Mid1+1, High)
end,
end,
Mid = Mid1.</lang>
Mid = Mid1.</syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
'''Recursive'''
'''Recursive'''
<lang PicoLisp>(de recursiveSearch (Val Lst Len)
<syntaxhighlight lang=PicoLisp>(de recursiveSearch (Val Lst Len)
(unless (=0 Len)
(unless (=0 Len)
(let (N (inc (/ Len 2)) L (nth Lst N))
(let (N (inc (/ Len 2)) L (nth Lst N))
Line 5,208: Line 5,208:
((> Val (car L))
((> Val (car L))
(recursiveSearch Val (cdr L) (- Len N)) )
(recursiveSearch Val (cdr L) (- Len N)) )
(T (recursiveSearch Val Lst (dec N))) ) ) ) )</lang>
(T (recursiveSearch Val Lst (dec N))) ) ) ) )</syntaxhighlight>
Output:
Output:
<pre>: (recursiveSearch 5 (2 3 5 8 "abc" "klm" "xyz" (7) (a b)) 9)
<pre>: (recursiveSearch 5 (2 3 5 8 "abc" "klm" "xyz" (7) (a b)) 9)
Line 5,217: Line 5,217:
-> NIL</pre>
-> NIL</pre>
'''Iterative'''
'''Iterative'''
<lang PicoLisp>(de iterativeSearch (Val Lst Len)
<syntaxhighlight lang=PicoLisp>(de iterativeSearch (Val Lst Len)
(use (N L)
(use (N L)
(loop
(loop
Line 5,227: Line 5,227:
(if (> Val (car L))
(if (> Val (car L))
(setq Lst (cdr L) Len (- Len N))
(setq Lst (cdr L) Len (- Len N))
(setq Len (dec N)) ) ) ) )</lang>
(setq Len (dec N)) ) ) ) )</syntaxhighlight>
Output:
Output:
<pre>: (iterativeSearch 5 (2 3 5 8 "abc" "klm" "xyz" (7) (a b)) 9)
<pre>: (iterativeSearch 5 (2 3 5 8 "abc" "klm" "xyz" (7) (a b)) 9)
Line 5,237: Line 5,237:


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang PL/I>/* A binary search of list A for element M */
<syntaxhighlight lang=PL/I>/* A binary search of list A for element M */
search: procedure (A, M) returns (fixed binary);
search: procedure (A, M) returns (fixed binary);
declare (A(*), M) fixed binary;
declare (A(*), M) fixed binary;
Line 5,252: Line 5,252:
end;
end;
return (lbound(A,1)-1);
return (lbound(A,1)-1);
end search;</lang>
end search;</syntaxhighlight>


=={{header|Pop11}}==
=={{header|Pop11}}==
'''Iterative'''
'''Iterative'''
<lang pop11>define BinarySearch(A, value);
<syntaxhighlight lang=pop11>define BinarySearch(A, value);
lvars low = 1, high = length(A), mid;
lvars low = 1, high = length(A), mid;
while low <= high do
while low <= high do
Line 5,276: Line 5,276:
BinarySearch(A, 4) =>
BinarySearch(A, 4) =>
BinarySearch(A, 5) =>
BinarySearch(A, 5) =>
BinarySearch(A, 8) =></lang>
BinarySearch(A, 8) =></syntaxhighlight>
'''Recursive'''
'''Recursive'''
<lang pop11>define BinarySearch(A, value);
<syntaxhighlight lang=pop11>define BinarySearch(A, value);
define do_it(low, high);
define do_it(low, high);
if high < low then
if high < low then
Line 5,293: Line 5,293:
enddefine;
enddefine;
do_it(1, length(A));
do_it(1, length(A));
enddefine;</lang>
enddefine;</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang PowerShell>
<syntaxhighlight lang=PowerShell>
function BinarySearch-Iterative ([int[]]$Array, [int]$Value)
function BinarySearch-Iterative ([int[]]$Array, [int]$Value)
{
{
Line 5,363: Line 5,363:
}
}
}
}
</syntaxhighlight>
</lang>
<lang PowerShell>
<syntaxhighlight lang=PowerShell>
Show-SearchResult -Array 10, 28, 41, 46, 58, 74, 76, 86, 89, 98 -Search 41 -Function Iterative
Show-SearchResult -Array 10, 28, 41, 46, 58, 74, 76, 86, 89, 98 -Search 41 -Function Iterative
Show-SearchResult -Array 10, 28, 41, 46, 58, 74, 76, 86, 89, 98 -Search 99 -Function Iterative
Show-SearchResult -Array 10, 28, 41, 46, 58, 74, 76, 86, 89, 98 -Search 99 -Function Iterative
Show-SearchResult -Array 10, 28, 41, 46, 58, 74, 76, 86, 89, 98 -Search 86 -Function Recursive
Show-SearchResult -Array 10, 28, 41, 46, 58, 74, 76, 86, 89, 98 -Search 86 -Function Recursive
Show-SearchResult -Array 10, 28, 41, 46, 58, 74, 76, 86, 89, 98 -Search 11 -Function Recursive
Show-SearchResult -Array 10, 28, 41, 46, 58, 74, 76, 86, 89, 98 -Search 11 -Function Recursive
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 5,380: Line 5,380:
=={{header|Prolog}}==
=={{header|Prolog}}==
Tested with Gnu-Prolog.
Tested with Gnu-Prolog.
<lang Prolog>bin_search(Elt,List,Result):-
<syntaxhighlight lang=Prolog>bin_search(Elt,List,Result):-
length(List,N), bin_search_inner(Elt,List,1,N,Result).
length(List,N), bin_search_inner(Elt,List,1,N,Result).
Line 5,402: Line 5,402:
MidElt > Elt,
MidElt > Elt,
NewEnd is Mid-1,
NewEnd is Mid-1,
bin_search_inner(Elt,List,Begin,NewEnd,Result).</lang>
bin_search_inner(Elt,List,Begin,NewEnd,Result).</syntaxhighlight>


{{out|Output examples}}
{{out|Output examples}}
Line 5,413: Line 5,413:
=={{header|PureBasic}}==
=={{header|PureBasic}}==
Both recursive and iterative procedures are included and called in the code below.
Both recursive and iterative procedures are included and called in the code below.
<lang PureBasic>#Recursive = 0 ;recursive binary search method
<syntaxhighlight lang=PureBasic>#Recursive = 0 ;recursive binary search method
#Iterative = 1 ;iterative binary search method
#Iterative = 1 ;iterative binary search method
#NotFound = -1 ;search result if item not found
#NotFound = -1 ;search result if item not found
Line 5,499: Line 5,499:
Input()
Input()
CloseConsole()
CloseConsole()
EndIf</lang>
EndIf</syntaxhighlight>
Sample output:
Sample output:
<pre>
<pre>
Line 5,515: Line 5,515:
=={{header|Python}}==
=={{header|Python}}==
===Python: Iterative===
===Python: Iterative===
<lang python>def binary_search(l, value):
<syntaxhighlight lang=python>def binary_search(l, value):
low = 0
low = 0
high = len(l)-1
high = len(l)-1
Line 5,523: Line 5,523:
elif l[mid] < value: low = mid+1
elif l[mid] < value: low = mid+1
else: return mid
else: return mid
return -1</lang>
return -1</syntaxhighlight>


We can also generalize this kind of binary search from direct matches to searches using a custom comparator function.
We can also generalize this kind of binary search from direct matches to searches using a custom comparator function.
In addition to a search for a particular word in an AZ-sorted list, for example, we could also perform a binary search for a word of a given '''length''' (in a word-list sorted by rising length), or for a particular value of any other comparable property of items in a suitably sorted list:
In addition to a search for a particular word in an AZ-sorted list, for example, we could also perform a binary search for a word of a given '''length''' (in a word-list sorted by rising length), or for a particular value of any other comparable property of items in a suitably sorted list:


<lang python># findIndexBinary :: (a -> Ordering) -> [a] -> Maybe Int
<syntaxhighlight lang=python># findIndexBinary :: (a -> Ordering) -> [a] -> Maybe Int
def findIndexBinary(p):
def findIndexBinary(p):
def isFound(bounds):
def isFound(bounds):
Line 5,618: Line 5,618:
if __name__ == '__main__':
if __name__ == '__main__':
main()
main()
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>Word found at index 6
<pre>Word found at index 6
Line 5,624: Line 5,624:


===Python: Recursive===
===Python: Recursive===
<lang python>def binary_search(l, value, low = 0, high = -1):
<syntaxhighlight lang=python>def binary_search(l, value, low = 0, high = -1):
if not l: return -1
if not l: return -1
if(high == -1): high = len(l)-1
if(high == -1): high = len(l)-1
Line 5,633: Line 5,633:
if l[mid] > value: return binary_search(l, value, low, mid-1)
if l[mid] > value: return binary_search(l, value, low, mid-1)
elif l[mid] < value: return binary_search(l, value, mid+1, high)
elif l[mid] < value: return binary_search(l, value, mid+1, high)
else: return mid</lang>
else: return mid</syntaxhighlight>


Generalizing again with a custom comparator function (see preamble to second iterative version above).
Generalizing again with a custom comparator function (see preamble to second iterative version above).
Line 5,639: Line 5,639:
This time using the recursive definition:
This time using the recursive definition:


<lang python># findIndexBinary_ :: (a -> Ordering) -> [a] -> Maybe Int
<syntaxhighlight lang=python># findIndexBinary_ :: (a -> Ordering) -> [a] -> Maybe Int
def findIndexBinary_(p):
def findIndexBinary_(p):
def go(xs):
def go(xs):
Line 5,706: Line 5,706:
'Word of given length found at index ' + str(mb2)
'Word of given length found at index ' + str(mb2)
)
)
)</lang>
)</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Word found at index 9
<pre>Word found at index 9
Line 5,713: Line 5,713:
===Python: Library===
===Python: Library===
<br>Python's <code>bisect</code> module provides binary search functions
<br>Python's <code>bisect</code> module provides binary search functions
<lang python>index = bisect.bisect_left(list, item) # leftmost insertion point
<syntaxhighlight lang=python>index = bisect.bisect_left(list, item) # leftmost insertion point
index = bisect.bisect_right(list, item) # rightmost insertion point
index = bisect.bisect_right(list, item) # rightmost insertion point
index = bisect.bisect(list, item) # same as bisect_right
index = bisect.bisect(list, item) # same as bisect_right
Line 5,720: Line 5,720:
bisect.insort_left(list, item)
bisect.insort_left(list, item)
bisect.insort_right(list, item)
bisect.insort_right(list, item)
bisect.insort(list, item)</lang>
bisect.insort(list, item)</syntaxhighlight>


====Python: Alternate====
====Python: Alternate====
Complete binary search function with python's <code>bisect</code> module:
Complete binary search function with python's <code>bisect</code> module:


<lang python>from bisect import bisect_left
<syntaxhighlight lang=python>from bisect import bisect_left


def binary_search(a, x, lo=0, hi=None): # can't use a to specify default for hi
def binary_search(a, x, lo=0, hi=None): # can't use a to specify default for hi
hi = hi if hi is not None else len(a) # hi defaults to len(a)
hi = hi if hi is not None else len(a) # hi defaults to len(a)
pos = bisect_left(a,x,lo,hi) # find insertion position
pos = bisect_left(a,x,lo,hi) # find insertion position
return (pos if pos != hi and a[pos] == x else -1) # don't walk off the end</lang>
return (pos if pos != hi and a[pos] == x else -1) # don't walk off the end</syntaxhighlight>


===Python: Approximate binary search===
===Python: Approximate binary search===
Returns the nearest item of list l to value.
Returns the nearest item of list l to value.
<lang python>def binary_search(l, value):
<syntaxhighlight lang=python>def binary_search(l, value):
low = 0
low = 0
high = len(l)-1
high = len(l)-1
Line 5,745: Line 5,745:
else:
else:
return mid
return mid
return high if abs(l[high] - value) < abs(l[low] - value) else low</lang>
return high if abs(l[high] - value) < abs(l[low] - value) else low</syntaxhighlight>


=={{header|Quackery}}==
=={{header|Quackery}}==
Written from pseudocode for rightmost insertion point, iterative.
Written from pseudocode for rightmost insertion point, iterative.


<lang Quackery> [ stack ] is value.bs ( --> n )
<syntaxhighlight lang=Quackery> [ stack ] is value.bs ( --> n )
[ stack ] is nest.bs ( --> n )
[ stack ] is nest.bs ( --> n )
[ stack ] is test.bs ( --> n )
[ stack ] is test.bs ( --> n )
Line 5,781: Line 5,781:
[ say " could go into position " ]
[ say " could go into position " ]
echo
echo
say "." cr ] is task ( [ n --> n )</lang>
say "." cr ] is task ( [ n --> n )</syntaxhighlight>


{{out}}
{{out}}
Line 5,797: Line 5,797:
=={{header|R}}==
=={{header|R}}==
'''Recursive'''
'''Recursive'''
<lang R>BinSearch <- function(A, value, low, high) {
<syntaxhighlight lang=R>BinSearch <- function(A, value, low, high) {
if ( high < low ) {
if ( high < low ) {
return(NULL)
return(NULL)
Line 5,809: Line 5,809:
mid
mid
}
}
}</lang>
}</syntaxhighlight>
'''Iterative'''
'''Iterative'''
<lang R>IterBinSearch <- function(A, value) {
<syntaxhighlight lang=R>IterBinSearch <- function(A, value) {
low = 1
low = 1
high = length(A)
high = length(A)
Line 5,825: Line 5,825:
}
}
NULL
NULL
}</lang>
}</syntaxhighlight>
'''Example'''
'''Example'''
<lang R>a <- 1:100
<syntaxhighlight lang=R>a <- 1:100
IterBinSearch(a, 50)
IterBinSearch(a, 50)
BinSearch(a, 50, 1, length(a)) # output 50
BinSearch(a, 50, 1, length(a)) # output 50
IterBinSearch(a, 101) # outputs NULL</lang>
IterBinSearch(a, 101) # outputs NULL</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>
<syntaxhighlight lang=racket>
#lang racket
#lang racket
(define (binary-search x v)
(define (binary-search x v)
Line 5,847: Line 5,847:
[else m])]))
[else m])]))
(loop 0 (vector-length v)))
(loop 0 (vector-length v)))
</syntaxhighlight>
</lang>
Examples:
Examples:
<pre>
<pre>
Line 5,857: Line 5,857:
(formerly Perl 6)
(formerly Perl 6)
With either of the below implementations of <code>binary_search</code>, one could write a function to search any object that does <code>Positional</code> this way:
With either of the below implementations of <code>binary_search</code>, one could write a function to search any object that does <code>Positional</code> this way:
<lang perl6>sub search (@a, $x --> Int) {
<syntaxhighlight lang=raku line>sub search (@a, $x --> Int) {
binary_search { $x cmp @a[$^i] }, 0, @a.end
binary_search { $x cmp @a[$^i] }, 0, @a.end
}</lang>
}</syntaxhighlight>
'''Iterative'''
'''Iterative'''
{{works with|Rakudo|2015.12}}
{{works with|Rakudo|2015.12}}
<lang perl6>sub binary_search (&p, Int $lo is copy, Int $hi is copy --> Int) {
<syntaxhighlight lang=raku line>sub binary_search (&p, Int $lo is copy, Int $hi is copy --> Int) {
until $lo > $hi {
until $lo > $hi {
my Int $mid = ($lo + $hi) div 2;
my Int $mid = ($lo + $hi) div 2;
Line 5,872: Line 5,872:
}
}
fail;
fail;
}</lang>
}</syntaxhighlight>
'''Recursive'''
'''Recursive'''
{{trans|Haskell}}
{{trans|Haskell}}
{{works with|Rakudo|2015.12}}
{{works with|Rakudo|2015.12}}
<lang perl6>sub binary_search (&p, Int $lo, Int $hi --> Int) {
<syntaxhighlight lang=raku line>sub binary_search (&p, Int $lo, Int $hi --> Int) {
$lo <= $hi or fail;
$lo <= $hi or fail;
my Int $mid = ($lo + $hi) div 2;
my Int $mid = ($lo + $hi) div 2;
Line 5,884: Line 5,884:
default { $mid }
default { $mid }
}
}
}</lang>
}</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 5,890: Line 5,890:
Incidentally, REXX doesn't care if the values in the list are integers (or even numbers), as long as they're in order.
Incidentally, REXX doesn't care if the values in the list are integers (or even numbers), as long as they're in order.
<br><br>(includes the extra credit)
<br><br>(includes the extra credit)
<lang rexx>/*REXX program finds a value in a list of integers using an iterative binary search.*/
<syntaxhighlight lang=rexx>/*REXX program finds a value in a list of integers using an iterative binary search.*/
@= 3 7 13 19 23 31 43 47 61 73 83 89 103 109 113 131 139 151 167 181,
@= 3 7 13 19 23 31 43 47 61 73 83 89 103 109 113 131 139 151 167 181,
193 199 229 233 241 271 283 293 313 317 337 349 353 359 383 389 401 409 421 433,
193 199 229 233 241 271 283 293 313 317 337 349 353 359 383 389 401 409 421 433,
Line 5,919: Line 5,919:
if ?=y then return mid
if ?=y then return mid
if y>? then return binarySearch(low, mid-1)
if y>? then return binarySearch(low, mid-1)
return binarySearch(mid+1, high)</lang>
return binarySearch(mid+1, high)</syntaxhighlight>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 499.1 </tt>}}
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 499.1 </tt>}}
<pre>
<pre>
Line 5,933: Line 5,933:
===iterative version===
===iterative version===
(includes the extra credit)
(includes the extra credit)
<lang rexx>/*REXX program finds a value in a list of integers using an iterative binary search.*/
<syntaxhighlight lang=rexx>/*REXX program finds a value in a list of integers using an iterative binary search.*/
@= 3 7 13 19 23 31 43 47 61 73 83 89 103 109 113 131 139 151 167 181,
@= 3 7 13 19 23 31 43 47 61 73 83 89 103 109 113 131 139 151 167 181,
193 199 229 233 241 271 283 293 313 317 337 349 353 359 383 389 401 409 421 433,
193 199 229 233 241 271 283 293 313 317 337 349 353 359 383 389 401 409 421 433,
Line 5,957: Line 5,957:
end /*while*/
end /*while*/


say ? " wasn't found in the list." /*stick a fork in it, we're all done. */</lang>
say ? " wasn't found in the list." /*stick a fork in it, we're all done. */</syntaxhighlight>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> -314 </tt>}}
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> -314 </tt>}}
<pre>
<pre>
Line 5,972: Line 5,972:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang=ring>
decimals(0)
decimals(0)
array = [7, 14, 21, 28, 35, 42, 49, 56, 63, 70]
array = [7, 14, 21, 28, 35, 42, 49, 56, 63, 70]
Line 6,003: Line 6,003:
return -1
return -1
ok
ok
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 6,011: Line 6,011:
=={{header|Ruby}}==
=={{header|Ruby}}==
'''Recursive'''
'''Recursive'''
<lang ruby>class Array
<syntaxhighlight lang=ruby>class Array
def binary_search(val, low=0, high=(length - 1))
def binary_search(val, low=0, high=(length - 1))
return nil if high < low
return nil if high < low
Line 6,034: Line 6,034:
puts "#{val} not found in array"
puts "#{val} not found in array"
end
end
end</lang>
end</syntaxhighlight>
'''Iterative'''
'''Iterative'''
<lang ruby>class Array
<syntaxhighlight lang=ruby>class Array
def binary_search_iterative(val)
def binary_search_iterative(val)
low, high = 0, length - 1
low, high = 0, length - 1
Line 6,063: Line 6,063:
puts "#{val} not found in array"
puts "#{val} not found in array"
end
end
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 6,074: Line 6,074:
'''Built in'''
'''Built in'''
Since Ruby 2.0, arrays ship with a binary search method "bsearch":
Since Ruby 2.0, arrays ship with a binary search method "bsearch":
<lang ruby>haystack = [0,1,4,5,6,7,8,9,12,26,45,67,78,90,98,123,211,234,456,769,865,2345,3215,14345,24324]
<syntaxhighlight lang=ruby>haystack = [0,1,4,5,6,7,8,9,12,26,45,67,78,90,98,123,211,234,456,769,865,2345,3215,14345,24324]
needles = [0,42,45,24324,99999]
needles = [0,42,45,24324,99999]


needles.select{|needle| haystack.bsearch{|hay| needle <=> hay} } # => [0, 45, 24324]
needles.select{|needle| haystack.bsearch{|hay| needle <=> hay} } # => [0, 45, 24324]
</lang>Which is 60% faster than "needles & haystack".
</syntaxhighlight>Which is 60% faster than "needles & haystack".


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
'''Recursive'''
'''Recursive'''
<lang runbasic>dim theArray(100)
<syntaxhighlight lang=runbasic>dim theArray(100)
global theArray
global theArray
for i = 1 to 100
for i = 1 to 100
Line 6,099: Line 6,099:
if val = theArray(middle) then binarySearch = middle
if val = theArray(middle) then binarySearch = middle
END IF
END IF
END FUNCTION</lang>
END FUNCTION</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
'''Iterative'''
'''Iterative'''
<lang rust>fn binary_search<T:PartialOrd>(v: &[T], searchvalue: T) -> Option<T> {
<syntaxhighlight lang=rust>fn binary_search<T:PartialOrd>(v: &[T], searchvalue: T) -> Option<T> {
let mut lower = 0 as usize;
let mut lower = 0 as usize;
let mut upper = v.len() - 1;
let mut upper = v.len() - 1;
Line 6,119: Line 6,119:


None
None
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
'''Recursive'''
'''Recursive'''
<lang scala>def binarySearch[A <% Ordered[A]](a: IndexedSeq[A], v: A) = {
<syntaxhighlight lang=scala>def binarySearch[A <% Ordered[A]](a: IndexedSeq[A], v: A) = {
def recurse(low: Int, high: Int): Option[Int] = (low + high) / 2 match {
def recurse(low: Int, high: Int): Option[Int] = (low + high) / 2 match {
case _ if high < low => None
case _ if high < low => None
Line 6,131: Line 6,131:
}
}
recurse(0, a.size - 1)
recurse(0, a.size - 1)
}</lang>
}</syntaxhighlight>
'''Iterative'''
'''Iterative'''
<lang scala>def binarySearch[T](xs: Seq[T], x: T)(implicit ordering: Ordering[T]): Option[Int] = {
<syntaxhighlight lang=scala>def binarySearch[T](xs: Seq[T], x: T)(implicit ordering: Ordering[T]): Option[Int] = {
var low: Int = 0
var low: Int = 0
var high: Int = xs.size - 1
var high: Int = xs.size - 1
Line 6,144: Line 6,144:
}
}
None //not found
None //not found
}</lang>
}</syntaxhighlight>
'''Test'''
'''Test'''
<lang scala>def testBinarySearch(n: Int) = {
<syntaxhighlight lang=scala>def testBinarySearch(n: Int) = {
val odds = 1 to n by 2
val odds = 1 to n by 2
val result = (0 to n).flatMap(binarySearch(odds, _))
val result = (0 to n).flatMap(binarySearch(odds, _))
Line 6,155: Line 6,155:
}
}


def main() = testBinarySearch(12)</lang>
def main() = testBinarySearch(12)</syntaxhighlight>
Output:
Output:
<pre>Range(1, 3, 5, 7, 9, 11) are odd natural numbers
<pre>Range(1, 3, 5, 7, 9, 11) are odd natural numbers
Line 6,167: Line 6,167:
=={{header|Scheme}}==
=={{header|Scheme}}==
'''Recursive'''
'''Recursive'''
<lang scheme>(define (binary-search value vector)
<syntaxhighlight lang=scheme>(define (binary-search value vector)
(let helper ((low 0)
(let helper ((low 0)
(high (- (vector-length vector) 1)))
(high (- (vector-length vector) 1)))
Line 6,177: Line 6,177:
((< (vector-ref vector middle) value)
((< (vector-ref vector middle) value)
(helper (+ middle 1) high))
(helper (+ middle 1) high))
(else middle))))))</lang>
(else middle))))))</syntaxhighlight>
Example:
Example:
<pre>
<pre>
Line 6,190: Line 6,190:
=={{header|Seed7}}==
=={{header|Seed7}}==
'''Iterative'''
'''Iterative'''
<lang seed7>const func integer: binarySearchIterative (in array elemType: arr, in elemType: aKey) is func
<syntaxhighlight lang=seed7>const func integer: binarySearchIterative (in array elemType: arr, in elemType: aKey) is func
result
result
var integer: result is 0;
var integer: result is 0;
Line 6,209: Line 6,209:
end if;
end if;
end while;
end while;
end func;</lang>
end func;</syntaxhighlight>
'''Recursive'''
'''Recursive'''
<lang seed7>const func integer: binarySearch (in array elemType: arr, in elemType: aKey, in integer: low, in integer: high) is func
<syntaxhighlight lang=seed7>const func integer: binarySearch (in array elemType: arr, in elemType: aKey, in integer: low, in integer: high) is func
result
result
var integer: result is 0;
var integer: result is 0;
Line 6,226: Line 6,226:


const func integer: binarySearchRecursive (in array elemType: arr, in elemType: aKey) is
const func integer: binarySearchRecursive (in array elemType: arr, in elemType: aKey) is
return binarySearch(arr, aKey, 1, length(arr));</lang>
return binarySearch(arr, aKey, 1, length(arr));</syntaxhighlight>


=={{header|SequenceL}}==
=={{header|SequenceL}}==
'''Recursive'''
'''Recursive'''
<lang sequencel>binarySearch(A(1), value(0), low(0), high(0)) :=
<syntaxhighlight lang=sequencel>binarySearch(A(1), value(0), low(0), high(0)) :=
let
let
mid := low + (high - low) / 2;
mid := low + (high - low) / 2;
Line 6,240: Line 6,240:
binarySearch(A, value, mid + 1, high) when A[mid] < value
binarySearch(A, value, mid + 1, high) when A[mid] < value
else
else
mid;</lang>
mid;</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
Iterative:
Iterative:
<lang ruby>func binary_search(a, i) {
<syntaxhighlight lang=ruby>func binary_search(a, i) {
var l = 0
var l = 0
Line 6,257: Line 6,257:
return -1
return -1
}</lang>
}</syntaxhighlight>
Recursive:
Recursive:
<lang ruby>func binary_search(arr, value, low=0, high=arr.end) {
<syntaxhighlight lang=ruby>func binary_search(arr, value, low=0, high=arr.end) {
high < low && return -1
high < low && return -1
var middle = ((high+low) // 2)
var middle = ((high+low) // 2)
Line 6,274: Line 6,274:
}
}
}
}
}</lang>
}</syntaxhighlight>


Usage:
Usage:
<lang ruby>say binary_search([34, 42, 55, 778], 55); #=> 2</lang>
<syntaxhighlight lang=ruby>say binary_search([34, 42, 55, 778], 55); #=> 2</syntaxhighlight>


=={{header|Simula}}==
=={{header|Simula}}==
<lang simula>BEGIN
<syntaxhighlight lang=simula>BEGIN




Line 6,367: Line 6,367:
END;
END;


END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 6,408: Line 6,408:


The first version has a postcondition that if Found is True the Position value returned is correct. This version also has a number of 'check' annotations. These are inserted to allow the Simplifier to prove all the verification conditions. See [[SPARK_Proof_Process|the SPARK Proof Process]].
The first version has a postcondition that if Found is True the Position value returned is correct. This version also has a number of 'check' annotations. These are inserted to allow the Simplifier to prove all the verification conditions. See [[SPARK_Proof_Process|the SPARK Proof Process]].
<lang Ada>package Binary_Searches is
<syntaxhighlight lang=Ada>package Binary_Searches is


subtype Item_Type is Integer; -- From specs.
subtype Item_Type is Integer; -- From specs.
Line 6,504: Line 6,504:
end Search;
end Search;


end Binary_Searches;</lang>
end Binary_Searches;</syntaxhighlight>
The second version of the package has a stronger postcondition on Search, which also states that if Found is False then there is no value in Source equal to Item. This postcondition cannot be proved without a precondition that Source is ordered. This version needs four user rules (see [[SPARK_Proof_Process|the SPARK Proof Process]]) to be provided to the Simplifier so that it can prove all the verification conditions.
The second version of the package has a stronger postcondition on Search, which also states that if Found is False then there is no value in Source equal to Item. This postcondition cannot be proved without a precondition that Source is ordered. This version needs four user rules (see [[SPARK_Proof_Process|the SPARK Proof Process]]) to be provided to the Simplifier so that it can prove all the verification conditions.
<lang Ada>package Binary_Searches is
<syntaxhighlight lang=Ada>package Binary_Searches is


subtype Item_Type is Integer; -- From specs.
subtype Item_Type is Integer; -- From specs.
Line 6,595: Line 6,595:
end Search;
end Search;


end Binary_Searches;</lang>
end Binary_Searches;</syntaxhighlight>
The user rules for this version of the package (written in FDL, a language for modelling algorithms).
The user rules for this version of the package (written in FDL, a language for modelling algorithms).
<pre>binary_search_rule(1): (X + Y) div 2 >= X
<pre>binary_search_rule(1): (X + Y) div 2 >= X
Line 6,628: Line 6,628:
</pre>
</pre>
The test program:
The test program:
<lang Ada>with Binary_Searches;
<syntaxhighlight lang=Ada>with Binary_Searches;
with SPARK_IO;
with SPARK_IO;


Line 6,712: Line 6,712:
Run_Search (Source => Array_Type9'(1, 2, 3, 4, 5, 6, 7, 8, 9), Item => 6);
Run_Search (Source => Array_Type9'(1, 2, 3, 4, 5, 6, 7, 8, 9), Item => 6);
end Test_Binary_Search;
end Test_Binary_Search;
</syntaxhighlight>
</lang>


Test output (for the last three tests the array is indexed from 91):
Test output (for the last three tests the array is indexed from 91):
Line 6,727: Line 6,727:
=={{header|Standard ML}}==
=={{header|Standard ML}}==
'''Recursive'''
'''Recursive'''
<lang sml>fun binary_search cmp (key, arr) =
<syntaxhighlight lang=sml>fun binary_search cmp (key, arr) =
let
let
fun aux slice =
fun aux slice =
Line 6,743: Line 6,743:
in
in
aux (ArraySlice.full arr)
aux (ArraySlice.full arr)
end</lang>
end</syntaxhighlight>
Usage:
Usage:
<pre>
<pre>
Line 6,785: Line 6,785:
=={{header|Swift}}==
=={{header|Swift}}==
'''Recursive'''
'''Recursive'''
<lang swift>func binarySearch<T: Comparable>(xs: [T], x: T) -> Int? {
<syntaxhighlight lang=swift>func binarySearch<T: Comparable>(xs: [T], x: T) -> Int? {
var recurse: ((Int, Int) -> Int?)!
var recurse: ((Int, Int) -> Int?)!
recurse = {(low, high) in switch (low + high) / 2 {
recurse = {(low, high) in switch (low + high) / 2 {
Line 6,794: Line 6,794:
}}
}}
return recurse(0, xs.count - 1)
return recurse(0, xs.count - 1)
}</lang>
}</syntaxhighlight>
'''Iterative'''
'''Iterative'''
<lang swift>func binarySearch<T: Comparable>(xs: [T], x: T) -> Int? {
<syntaxhighlight lang=swift>func binarySearch<T: Comparable>(xs: [T], x: T) -> Int? {
var (low, high) = (0, xs.count - 1)
var (low, high) = (0, xs.count - 1)
while low <= high {
while low <= high {
Line 6,806: Line 6,806:
}
}
return nil
return nil
}</lang>
}</syntaxhighlight>
'''Test'''
'''Test'''
<lang swift>func testBinarySearch(n: Int) {
<syntaxhighlight lang=swift>func testBinarySearch(n: Int) {
let odds = Array(stride(from: 1, through: n, by: 2))
let odds = Array(stride(from: 1, through: n, by: 2))
let result = flatMap(0...n) {binarySearch(odds, $0)}
let result = flatMap(0...n) {binarySearch(odds, $0)}
Line 6,822: Line 6,822:
func flatMap<T, U>(source: [T], transform: (T) -> U?) -> [U] {
func flatMap<T, U>(source: [T], transform: (T) -> U?) -> [U] {
return source.reduce([]) {(var xs, x) in if let x = transform(x) {xs.append(x)}; return xs}
return source.reduce([]) {(var xs, x) in if let x = transform(x) {xs.append(x)}; return xs}
}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>[1, 3, 5, 7, 9, 11] are odd natural numbers
<pre>[1, 3, 5, 7, 9, 11] are odd natural numbers
Line 6,834: Line 6,834:


=={{header|Symsyn}}==
=={{header|Symsyn}}==
<lang symsyn>
<syntaxhighlight lang=symsyn>


a : 1 : 2 : 27 : 44 : 46 : 57 : 77 : 154 : 212
a : 1 : 2 : 27 : 44 : 46 : 57 : 77 : 154 : 212
Line 6,865: Line 6,865:
"'result = ' R" []
"'result = ' R" []


</syntaxhighlight>
</lang>


=={{header|Tcl}}==
=={{header|Tcl}}==
ref: [http://wiki.tcl.tk/22796 Tcl wiki]
ref: [http://wiki.tcl.tk/22796 Tcl wiki]
<lang tcl>proc binSrch {lst x} {
<syntaxhighlight lang=tcl>proc binSrch {lst x} {
set len [llength $lst]
set len [llength $lst]
if {$len == 0} {
if {$len == 0} {
Line 6,893: Line 6,893:
puts "element $x found at index $idx"
puts "element $x found at index $idx"
}
}
}</lang>
}</syntaxhighlight>
Note also that, from Tcl 8.4 onwards, the <tt>lsearch</tt> command includes the <tt>-sorted</tt> option to enable binary searching of Tcl lists.
Note also that, from Tcl 8.4 onwards, the <tt>lsearch</tt> command includes the <tt>-sorted</tt> option to enable binary searching of Tcl lists.
<lang tcl>proc binarySearch {lst x} {
<syntaxhighlight lang=tcl>proc binarySearch {lst x} {
set idx [lsearch -sorted -exact $lst $x]
set idx [lsearch -sorted -exact $lst $x]
if {$idx == -1} {
if {$idx == -1} {
Line 6,902: Line 6,902:
puts "element $x found at index $idx"
puts "element $x found at index $idx"
}
}
}</lang>
}</syntaxhighlight>


=={{header|TI-83 BASIC}}==
=={{header|TI-83 BASIC}}==
<lang ti83b>PROGRAM:BINSEARC
<syntaxhighlight lang=ti83b>PROGRAM:BINSEARC
:Disp "INPUT A LIST:"
:Disp "INPUT A LIST:"
:Input L1
:Input L1
Line 6,931: Line 6,931:
:Disp A
:Disp A
:Disp "IS NOT IN"
:Disp "IS NOT IN"
:Disp L1</lang>
:Disp L1</syntaxhighlight>


=={{header|uBasic/4tH}}==
=={{header|uBasic/4tH}}==
{{trans|Run BASIC}}
{{trans|Run BASIC}}
The overflow is fixed - which is a bit of overkill, since uBasic/4tH has only one array of 256 elements.
The overflow is fixed - which is a bit of overkill, since uBasic/4tH has only one array of 256 elements.
<lang>For i = 1 To 100 ' Fill array with some values
<syntaxhighlight lang=text>For i = 1 To 100 ' Fill array with some values
@(i-1) = i
@(i-1) = i
Next
Next
Line 6,954: Line 6,954:
If a@ > @(d@) Then Return (FUNC(_binarySearch (a@, d@+1, c@)))
If a@ > @(d@) Then Return (FUNC(_binarySearch (a@, d@+1, c@)))
If a@ = @(d@) Then Return (d@) ' We found it, return index!
If a@ = @(d@) Then Return (d@) ' We found it, return index!
EndIf</lang>
EndIf</syntaxhighlight>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
Line 6,960: Line 6,960:
'''Reading values line by line'''
'''Reading values line by line'''


<lang bash>
<syntaxhighlight lang=bash>
#!/bin/ksh
#!/bin/ksh
# This should work on any clone of Bourne Shell, ksh is the fastest.
# This should work on any clone of Bourne Shell, ksh is the fastest.
Line 6,972: Line 6,972:
array[${#array[*]}]=$line
array[${#array[*]}]=$line
done
done
</syntaxhighlight>
</lang>




'''Iterative'''
'''Iterative'''
<lang bash>
<syntaxhighlight lang=bash>
left=0
left=0
right=$(($size - 1))
right=$(($size - 1))
Line 6,992: Line 6,992:
done
done
echo 'ERROR 404 : NOT FOUND'
echo 'ERROR 404 : NOT FOUND'
</syntaxhighlight>
</lang>


'''Recursive'''
'''Recursive'''
<lang> No code yet </lang>
<syntaxhighlight lang=text> No code yet </syntaxhighlight>


=={{header|UnixPipes}}==
=={{header|UnixPipes}}==
'''Parallel'''
'''Parallel'''
<lang bash>splitter() {
<syntaxhighlight lang=bash>splitter() {
a=$1; s=$2; l=$3; r=$4;
a=$1; s=$2; l=$3; r=$4;
mid=$(expr ${#a[*]} / 2);
mid=$(expr ${#a[*]} / 2);
Line 7,016: Line 7,016:
}
}


echo "1 2 3 4 6 7 8 9" | binsearch 6</lang>
echo "1 2 3 4 6 7 8 9" | binsearch 6</syntaxhighlight>


=={{header|VBA}}==
=={{header|VBA}}==
'''Recursive version''':
'''Recursive version''':
<lang vb>Public Function BinarySearch(a, value, low, high)
<syntaxhighlight lang=vb>Public Function BinarySearch(a, value, low, high)
'search for "value" in ordered array a(low..high)
'search for "value" in ordered array a(low..high)
'return index point if found, -1 if not found
'return index point if found, -1 if not found
Line 7,036: Line 7,036:
BinarySearch = midd
BinarySearch = midd
End If
End If
End Function</lang>
End Function</syntaxhighlight>
Here are some test functions:
Here are some test functions:
<lang vb>Public Sub testBinarySearch(n)
<syntaxhighlight lang=vb>Public Sub testBinarySearch(n)
Dim a(1 To 100)
Dim a(1 To 100)
'create an array with values = multiples of 10
'create an array with values = multiples of 10
Line 7,050: Line 7,050:
a = Array("AA", "Maestro", "Mario", "Master", "Mattress", "Mister", "Mistress", "ZZ")
a = Array("AA", "Maestro", "Mario", "Master", "Mattress", "Mister", "Mistress", "ZZ")
Debug.Print BinarySearch(a, w, LBound(a), UBound(a))
Debug.Print BinarySearch(a, w, LBound(a), UBound(a))
End Sub</lang>
End Sub</syntaxhighlight>
and sample output:
and sample output:
<pre>
<pre>
Line 7,068: Line 7,068:


'''Iterative version:'''
'''Iterative version:'''
<lang vb>Public Function BinarySearch2(a, value)
<syntaxhighlight lang=vb>Public Function BinarySearch2(a, value)
'search for "value" in array a
'search for "value" in array a
'return index point if found, -1 if not found
'return index point if found, -1 if not found
Line 7,086: Line 7,086:
Loop
Loop
BinarySearch2 = -1 'not found
BinarySearch2 = -1 'not found
End Function</lang>
End Function</syntaxhighlight>


=={{header|VBScript}}==
=={{header|VBScript}}==
{{trans|BASIC}}
{{trans|BASIC}}
'''Recursive'''
'''Recursive'''
<lang vb>Function binary_search(arr,value,lo,hi)
<syntaxhighlight lang=vb>Function binary_search(arr,value,lo,hi)
If hi < lo Then
If hi < lo Then
binary_search = 0
binary_search = 0
Line 7,117: Line 7,117:
WScript.StdOut.Write n & " not found"
WScript.StdOut.Write n & " not found"
WScript.StdOut.WriteLine
WScript.StdOut.WriteLine
End If</lang>
End If</syntaxhighlight>
{{out}}
{{out}}
'''Note: Array index starts at 0.'''
'''Note: Array index starts at 0.'''
Line 7,136: Line 7,136:
For this implementation, the numbers to be searched must be stored in current edit buffer, one number per line.
For this implementation, the numbers to be searched must be stored in current edit buffer, one number per line.
(Could be for example a csv table where the first column is used as key field.)
(Could be for example a csv table where the first column is used as key field.)
<lang vedit>// Main program for testing BINARY_SEARCH
<syntaxhighlight lang=vedit>// Main program for testing BINARY_SEARCH
#3 = Get_Num("Value to search: ")
#3 = Get_Num("Value to search: ")
EOF
EOF
Line 7,165: Line 7,165:
}
}
}
}
return(0) // not found</lang>
return(0) // not found</syntaxhighlight>


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
'''Iterative'''
'''Iterative'''
<lang vbnet>Function BinarySearch(ByVal A() As Integer, ByVal value As Integer) As Integer
<syntaxhighlight lang=vbnet>Function BinarySearch(ByVal A() As Integer, ByVal value As Integer) As Integer
Dim low As Integer = 0
Dim low As Integer = 0
Dim high As Integer = A.Length - 1
Dim high As Integer = A.Length - 1
Line 7,186: Line 7,186:


Return Nothing
Return Nothing
End Function</lang>
End Function</syntaxhighlight>
'''Recursive'''
'''Recursive'''
<lang vbnet>Function BinarySearch(ByVal A() As Integer, ByVal value As Integer, ByVal low As Integer, ByVal high As Integer) As Integer
<syntaxhighlight lang=vbnet>Function BinarySearch(ByVal A() As Integer, ByVal value As Integer, ByVal low As Integer, ByVal high As Integer) As Integer
Dim middle As Integer = 0
Dim middle As Integer = 0


Line 7,204: Line 7,204:
Return middle
Return middle
End If
End If
End Function</lang>
End Function</syntaxhighlight>


=={{header|Vlang}}==
=={{header|Vlang}}==
<lang vlang>fn binary_search_rec(a []f64, value f64, low int, high int) int { // recursive
<syntaxhighlight lang=vlang>fn binary_search_rec(a []f64, value f64, low int, high int) int { // recursive
if high <= low {
if high <= low {
return -1
return -1
Line 7,241: Line 7,241:
println(binary_search_it(f_list,9))
println(binary_search_it(f_list,9))
println(binary_search_it(f_list,15))
println(binary_search_it(f_list,15))
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 7,253: Line 7,253:
=={{header|Wortel}}==
=={{header|Wortel}}==
{{trans|JavaScript}}
{{trans|JavaScript}}
<lang wortel>; Recursive
<syntaxhighlight lang=wortel>; Recursive
@var rec &[a v l h] [
@var rec &[a v l h] [
@if < h l @return null
@if < h l @return null
Line 7,276: Line 7,276:
]
]
null
null
]</lang>
]</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>class BinarySearch {
<syntaxhighlight lang=ecmascript>class BinarySearch {
static recursive(a, value, low, high) {
static recursive(a, value, low, high) {
if (high < low) return -1
if (high < low) return -1
Line 7,326: Line 7,326:
System.print(" %(value) was not found in the array.")
System.print(" %(value) was not found in the array.")
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 7,344: Line 7,344:
{{trans|C}}
{{trans|C}}
{{works with|EXPL-32}}
{{works with|EXPL-32}}
<lang xpl0>
<syntaxhighlight lang=xpl0>
\Binary search
\Binary search
code CrLf=9, IntOut=11, Text=12;
code CrLf=9, IntOut=11, Text=12;
Line 7,404: Line 7,404:
PrintResult(X, I);
PrintResult(X, I);
end
end
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 7,413: Line 7,413:
=={{header|Yabasic}}==
=={{header|Yabasic}}==
{{trans|Lua}}
{{trans|Lua}}
<lang Yabasic>sub floor(n)
<syntaxhighlight lang=Yabasic>sub floor(n)
return int(n + .5)
return int(n + .5)
end sub
end sub
Line 7,444: Line 7,444:


print binarySearch(list(), 3)
print binarySearch(list(), 3)
print peek("millisrunning")</lang>
print peek("millisrunning")</syntaxhighlight>


=={{header|z/Arch Assembler}}==
=={{header|z/Arch Assembler}}==
This optimized version for z/Arch, uses six general regs and avoid branch misspredictions for high/low cases.
This optimized version for z/Arch, uses six general regs and avoid branch misspredictions for high/low cases.
<lang z/Archasm>* Binary search
<syntaxhighlight lang=z/Archasm>* Binary search
BINSRCH LA R5,TABLE Begin of table
BINSRCH LA R5,TABLE Begin of table
SR R2,R2 low = 0
SR R2,R2 low = 0
Line 7,464: Line 7,464:
LOCRH R3,R0 High? => HIGH = MID-1
LOCRH R3,R0 High? => HIGH = MID-1
LOCRL R2,R1 Low? => LOW = MID+1
LOCRL R2,R1 Low? => LOW = MID+1
J LOOP }</lang>
J LOOP }</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
This algorithm is tail recursive, which means it is both recursive and iterative (since tail recursion optimizes to a jump). Overflow is not possible because Ints (64 bit) are a lot bigger than the max length of a list.
This algorithm is tail recursive, which means it is both recursive and iterative (since tail recursion optimizes to a jump). Overflow is not possible because Ints (64 bit) are a lot bigger than the max length of a list.
<lang zkl>fcn bsearch(list,value){ // list is sorted
<syntaxhighlight lang=zkl>fcn bsearch(list,value){ // list is sorted
fcn(list,value, low,high){
fcn(list,value, low,high){
if (high < low) return(Void); // not found
if (high < low) return(Void); // not found
Line 7,476: Line 7,476:
return(mid); // found
return(mid); // found
}(list,value,0,list.len()-1);
}(list,value,0,list.len()-1);
}</lang>
}</syntaxhighlight>
<lang zkl>list:=T(1,3,5,7,9,11); println("Sorted values: ",list);
<syntaxhighlight lang=zkl>list:=T(1,3,5,7,9,11); println("Sorted values: ",list);
foreach i in ([0..12]){
foreach i in ([0..12]){
n:=bsearch(list,i);
n:=bsearch(list,i);
if (Void==n) println("Not found: ",i);
if (Void==n) println("Not found: ",i);
else println("found ",i," at index ",n);
else println("found ",i," at index ",n);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 7,504: Line 7,504:
{{trans|FreeBASIC}}
{{trans|FreeBASIC}}
Iterative method:
Iterative method:
<lang zxbasic>10 DATA 2,3,5,6,8,10,11,15,19,20
<syntaxhighlight lang=zxbasic>10 DATA 2,3,5,6,8,10,11,15,19,20
20 DIM t(10)
20 DIM t(10)
30 FOR i=1 TO 10
30 FOR i=1 TO 10
Line 7,523: Line 7,523:
180 IF idx=0 THEN PRINT " not found": RETURN
180 IF idx=0 THEN PRINT " not found": RETURN
190 PRINT " found at index ";idx: RETURN
190 PRINT " found at index ";idx: RETURN
</syntaxhighlight>
</lang>