Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,5 @@
---
category:
- Recursion
from: http://rosettacode.org/wiki/Binary_search
note: Classic CS problems and programs

View file

@ -0,0 +1,145 @@
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm.
As an analogy, consider the children's game "[[Guess the number/With feedback|guess a number]]." The scorer has a secret number, and will only tell the player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number.
As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number.
;Task:
Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also.
There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them.
All of the following code examples use an "inclusive" upper bound (i.e. <code>high = N-1</code> initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. <code>high = N</code> initially) by making the following simple changes (which simply increase <code>high</code> by 1):
* change <code>high = N-1</code> to <code>high = N</code>
* change <code>high = mid-1</code> to <code>high = mid</code>
* (for recursive algorithm) change <code>if (high < low)</code> to <code>if (high <= low)</code>
* (for iterative algorithm) change <code>while (low <= high)</code> to <code>while (low < high)</code>
;Traditional algorithm
The algorithms are as follows (from [[wp:Binary search algorithm|Wikipedia]]). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array).
'''Recursive Pseudocode''':
// initially called with low = 0, high = N-1
BinarySearch(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return not_found // value would be inserted at index "low"
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch(A, value, low, mid-1)
else if (A[mid] < value)
return BinarySearch(A, value, mid+1, high)
else
return mid
}
'''Iterative Pseudocode''':
BinarySearch(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else if (A[mid] < value)
low = mid + 1
else
return mid
}
return not_found // value would be inserted at index "low"
}
;Leftmost insertion point
The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level.
'''Recursive Pseudocode''':
// initially called with low = 0, high = N - 1
BinarySearch_Left(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] >= value)
return BinarySearch_Left(A, value, low, mid-1)
else
return BinarySearch_Left(A, value, mid+1, high)
}
'''Iterative Pseudocode''':
BinarySearch_Left(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value > A[i] for all i < low
value <= A[i] for all i > high
mid = (low + high) / 2
if (A[mid] >= value)
high = mid - 1
else
low = mid + 1
}
return low
}
;Rightmost insertion point
The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values.
'''Recursive Pseudocode''':
// initially called with low = 0, high = N - 1
BinarySearch_Right(A[0..N-1], value, low, high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return low
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch_Right(A, value, low, mid-1)
else
return BinarySearch_Right(A, value, mid+1, high)
}
'''Iterative Pseudocode''':
BinarySearch_Right(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
// invariants: value >= A[i] for all i < low
value < A[i] for all i > high
mid = (low + high) / 2
if (A[mid] > value)
high = mid - 1
else
low = mid + 1
}
return low
}
;Extra credit
Make sure it does not have overflow bugs.
The line in the pseudo-code above to calculate the mean of two integers:
<pre>mid = (low + high) / 2</pre>
could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and <code>low + high</code> overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result.
One way to fix it is to manually add half the range to the low number:
<pre>mid = low + (high - low) / 2</pre>
Even though this is mathematically equivalent to the above, it is not susceptible to overflow.
Another way for signed integers, possibly faster, is the following:
<pre>mid = (low + high) >>> 1</pre>
where <code> >>> </code> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift.
;Related task:
:* [[Guess the number/With Feedback (Player)]]
;See also:
:* [[wp:Binary search algorithm]]
:* [http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken].
<br><br>

View file

@ -0,0 +1,12 @@
F binary_search(l, value)
V low = 0
V high = l.len - 1
L low <= high
V mid = (low + high) I/ 2
I l[mid] > value
high = mid - 1
E I l[mid] < value
low = mid + 1
E
R mid
R -1

View file

@ -0,0 +1,71 @@
* Binary search 05/03/2017
BINSEAR CSECT
USING BINSEAR,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
MVC LOW,=H'1' low=1
MVC HIGH,=AL2((XVAL-T)/2) high=hbound(t)
SR R6,R6 i=0
MVI F,X'00' f=false
LH R4,LOW low
DO WHILE=(CH,R4,LE,HIGH) do while low<=high
LA R6,1(R6) i=i+1
LH R1,LOW low
AH R1,HIGH +high
SRA R1,1 /2 {by right shift}
STH R1,MID mid=(low+high)/2
SLA R1,1 *2
LH R7,T-2(R1) y=t(mid)
IF CH,R7,EQ,XVAL THEN if xval=y then
MVI F,X'01' f=true
B EXITDO leave
ENDIF , endif
IF CH,R7,GT,XVAL THEN if y>xval then
LH R2,MID mid
BCTR R2,0 -1
STH R2,HIGH high=mid-1
ELSE , else
LH R2,MID mid
LA R2,1(R2) +1
STH R2,LOW low=mid+1
ENDIF , endif
LH R4,LOW low
ENDDO , enddo
EXITDO EQU * exitdo:
XDECO R6,XDEC edit i
MVC PG(4),XDEC+8 output i
MVC PG+4(6),=C' loops'
XPRNT PG,L'PG print buffer
LH R1,XVAL xval
XDECO R1,XDEC edit xval
MVC PG(4),XDEC+8 output xval
IF CLI,F,EQ,X'01' THEN if f then
MVC PG+4(10),=C' found at '
LH R1,MID mid
XDECO R1,XDEC edit mid
MVC PG+14(4),XDEC+8 output mid
ELSE , else
MVC PG+4(20),=C' is not in the list.'
ENDIF , endif
XPRNT PG,L'PG print buffer
L R13,4(0,R13) restore previous savearea pointer
LM R14,R12,12(R13) restore previous context
XR R15,R15 rc=0
BR R14 exit
T DC H'3',H'7',H'13',H'19',H'23',H'31',H'43',H'47'
DC H'61',H'73',H'83',H'89',H'103',H'109',H'113',H'131'
DC H'139',H'151',H'167',H'181',H'193',H'199',H'229',H'233'
DC H'241',H'271',H'283',H'293',H'313',H'317',H'337',H'349'
XVAL DC H'229' <= search value
LOW DS H
HIGH DS H
MID DS H
F DS X flag
PG DC CL80' ' buffer
XDEC DS CL12 temp
YREGS
END BINSEAR

View file

@ -0,0 +1,102 @@
org 100h ; Entry for test code
jmp test
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Binary search in array of unsigned 8-bit integers
;; B = value to look for
;; HL = begin of array (low)
;; DE = end of array, inclusive (high)
;; The entry point is 'binsrch'
;; On return, HL = location of value (if contained
;; in array), or insertion point (if not)
binsrch_lo: inx h ; low = mid + 1
inx sp ; throw away 'low'
inx sp
binsrch: mov a,d ; low > high? (are we there yet?)
cmp h ; test high byte
rc
mov a,e ; test low byte
cmp l
rc
push h ; store 'low'
dad d ; mid = (low+high)>>1
mov a,h ; rotate the carry flag back in
rar ; to take care of any overflow
mov h,a
mov a,l
rar
mov l,a
mov a,m ; A[mid] >= value?
cmp b
jc binsrch_lo
xchg ; high = mid - 1
dcx d
pop h ; restore 'low'
jmp binsrch
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Test data
primes: db 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37
db 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83
db 89, 97, 101, 103, 107, 109, 113, 127, 131
db 137, 139, 149, 151, 157, 163, 167, 173, 179
db 181, 191, 193, 197, 199, 211, 223, 227, 229
db 233, 239, 241, 251
primes_last: equ $ - 1
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Test code (CP/M compatible)
yep: db ": yes", 13, 10, "$"
nope: db ": no", 13, 10, "$"
num_out: mov a,b ;; Output number in B as decimal
mvi c,100
call dgt_out
mvi c,10
call dgt_out
mvi c,1
dgt_out: mvi e,'0' - 1 ;; Output 100s, 10s or 1s
dgt_out_loop: inr e ;; (depending on C)
sub c
jnc dgt_out_loop
add c
e_out: push psw ;; Output character in E
push b ;; preserving working registers
mvi c,2
call 5
pop b
pop psw
ret
;; Main test code
test: mvi b,0 ; Test value
test_loop: call num_out ; Output current number to test
lxi h,primes ; Set up input for binary search
lxi d,primes_last
call binsrch ; Search for B in array
lxi d,nope ; Location of "no" string
mov a,b ; Check if location binsrch returned
cmp m ; contains the value we were looking for
jnz str_out ; If not, print the "no" string
lxi d,yep ; But if so, use location of "yes" string
str_out: push b ; Preserve B across CP/M call
mvi c,9 ; Print the string
call 5
pop b ; Restore B
inr b ; Test next value
jnz test_loop
rst 0

View file

@ -0,0 +1,236 @@
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program binSearch64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResult: .asciz "Value find at index : @ \n"
szCarriageReturn: .asciz "\n"
sMessRecursif: .asciz "Recursive search : \n"
sMessNotFound: .asciz "Value not found. \n"
TableNumber: .quad 4,6,7,10,11,15,22,30,35
.equ NBELEMENTS, (. - TableNumber) / 8
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
mov x0,4 // search first value
ldr x1,qAdrTableNumber // address number table
mov x2,NBELEMENTS // number of élements
bl bSearch
ldr x1,qAdrsZoneConv
bl conversion10 // décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
mov x0,#11 // search median value
ldr x1,qAdrTableNumber
mov x2,#NBELEMENTS
bl bSearch
ldr x1,qAdrsZoneConv
bl conversion10 // decimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
mov x0,#12 //value not found
ldr x1,qAdrTableNumber
mov x2,#NBELEMENTS
bl bSearch
cmp x0,#-1
bne 2f
ldr x0,qAdrsMessNotFound
bl affichageMess
b 3f
2:
ldr x1,qAdrsZoneConv
bl conversion10 // décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
3:
mov x0,#35 // search last value
ldr x1,qAdrTableNumber
mov x2,#NBELEMENTS
bl bSearch
ldr x1,qAdrsZoneConv
bl conversion10 // décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
/****************************************/
/* recursive */
/****************************************/
ldr x0,qAdrsMessRecursif
bl affichageMess // display message
mov x0,#4 // search first value
ldr x1,qAdrTableNumber
mov x2,#0 // low index of elements
mov x3,#NBELEMENTS - 1 // high index of elements
bl bSearchR
ldr x1,qAdrsZoneConv
bl conversion10 // décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
mov x0,#11
ldr x1,qAdrTableNumber
mov x2,#0
mov x3,#NBELEMENTS - 1
bl bSearchR
ldr x1,qAdrsZoneConv
bl conversion10 // décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
mov x0,#12
ldr x1,qAdrTableNumber
mov x2,#0
mov x3,#NBELEMENTS - 1
bl bSearchR
cmp x0,#-1
bne 4f
ldr x0,qAdrsMessNotFound
bl affichageMess
b 5f
4:
ldr x1,qAdrsZoneConv
bl conversion10 // décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
5:
mov x0,#35
ldr x1,qAdrTableNumber
mov x2,#0
mov x3,#NBELEMENTS - 1
bl bSearchR
ldr x1,qAdrsZoneConv
bl conversion10 // décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc #0 // perform the system call
//qAdrsMessValeur: .quad sMessValeur
qAdrsZoneConv: .quad sZoneConv
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsMessResult: .quad sMessResult
qAdrsMessRecursif: .quad sMessRecursif
qAdrsMessNotFound: .quad sMessNotFound
qAdrTableNumber: .quad TableNumber
/******************************************************************/
/* binary search iterative */
/******************************************************************/
/* x0 contains the value to search */
/* x1 contains the adress of table */
/* x2 contains the number of elements */
/* x0 return index or -1 if not find */
bSearch:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
mov x3,#0 // low index
sub x4,x2,#1 // high index = number of elements - 1
1:
cmp x3,x4
bgt 99f
add x2,x3,x4 // compute (low + high) /2
lsr x2,x2,#1
ldr x5,[x1,x2,lsl #3] // load value of table at index x2
cmp x5,x0
beq 98f
bgt 2f
add x3,x2,#1 // lower -> index low = index + 1
b 1b // and loop
2:
sub x4,x2,#1 // bigger -> index high = index - 1
b 1b // and loop
98:
mov x0,x2 // find !!!
b 100f
99:
mov x0,#-1 //not found
100:
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* binary search recursif */
/******************************************************************/
/* x0 contains the value to search */
/* x1 contains the adress of table */
/* x2 contains the low index of elements */
/* x3 contains the high index of elements */
/* x0 return index or -1 if not find */
bSearchR:
stp x2,lr,[sp,-16]! // save registers
stp x3,x4,[sp,-16]! // save registers
stp x5,x6,[sp,-16]! // save registers
cmp x3,x2 // index high < low ?
bge 1f
mov x0,#-1 // yes -> not found
b 100f
1:
add x4,x2,x3 // compute (low + high) /2
lsr x4,x4,#1
ldr x5,[x1,x4,lsl #3] // load value of table at index x4
cmp x5,x0
beq 99f
bgt 2f // bigger ?
add x2,x4,#1 // no new search with low = index + 1
bl bSearchR
b 100f
2: // bigger
sub x3,x4,#1 // new search with high = index - 1
bl bSearchR
b 100f
99:
mov x0,x4 // find !!!
b 100f
100:
ldp x5,x6,[sp],16 // restaur 2 registers
ldp x3,x4,[sp],16 // restaur 2 registers
ldp x2,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"

View file

@ -0,0 +1,61 @@
(defun defarray (name size initial-element)
(cons name
(compress1 name
(cons (list :HEADER
:DIMENSIONS (list size)
:MAXIMUM-LENGTH (1+ size)
:DEFAULT initial-element
:NAME name)
nil))))
(defconst *dim* 100000)
(defun array-name (array)
(first array))
(defun set-at (array i val)
(cons (array-name array)
(aset1 (array-name array)
(cdr array)
i
val)))
(defun populate-array-ordered (array n)
(if (zp n)
array
(populate-array-ordered (set-at array
(- *dim* n)
(- *dim* n))
(1- n))))
(include-book "arithmetic-3/top" :dir :system)
(defun binary-search-r (needle haystack low high)
(declare (xargs :measure (nfix (1+ (- high low)))))
(let* ((mid (floor (+ low high) 2))
(current (aref1 (array-name haystack)
(cdr haystack)
mid)))
(cond ((not (and (natp low) (natp high))) nil)
((= current needle)
mid)
((zp (1+ (- high low))) nil)
((> current needle)
(binary-search-r needle
haystack
low
(1- mid)))
(t (binary-search-r needle
haystack
(1+ mid)
high)))))
(defun binary-search (needle haystack)
(binary-search-r needle haystack 0
(maximum-length (array-name haystack)
(cdr haystack))))
(defun test-bsearch (needle)
(binary-search needle
(populate-array-ordered
(defarray 'haystack *dim* 0)
*dim*)))

View file

@ -0,0 +1,49 @@
BEGIN
MODE ELEMENT = STRING;
# Iterative: #
PROC iterative binary search = ([]ELEMENT hay stack, ELEMENT needle)INT: (
INT out,
low := LWB hay stack,
high := UPB hay stack;
WHILE low < high DO
INT mid := (low+high) OVER 2;
IF hay stack[mid] > needle THEN high := mid-1
ELIF hay stack[mid] < needle THEN low := mid+1
ELSE out:= mid; stop iteration FI
OD;
low EXIT
stop iteration:
out
);
# Recursive: #
PROC recursive binary search = ([]ELEMENT hay stack, ELEMENT needle)INT: (
IF LWB hay stack > UPB hay stack THEN
LWB hay stack
ELIF LWB hay stack = UPB hay stack THEN
IF hay stack[LWB hay stack] = needle THEN LWB hay stack
ELSE LWB hay stack FI
ELSE
INT mid := (LWB hay stack+UPB hay stack) OVER 2;
IF hay stack[mid] > needle THEN recursive binary search(hay stack[:mid-1], needle)
ELIF hay stack[mid] < needle THEN mid + recursive binary search(hay stack[mid+1:], needle)
ELSE mid FI
FI
);
# Test cases: #
test:(
ELEMENT needle = "mister";
[]ELEMENT hay stack = ("AA","Maestro","Mario","Master","Mattress","Mister","Mistress","ZZ"),
test cases = ("A","Master","Monk","ZZZ");
PROC test search = (PROC([]ELEMENT, ELEMENT)INT search, []ELEMENT test cases)VOID:
FOR case TO UPB test cases DO
ELEMENT needle = test cases[case];
INT index = search(hay stack, needle);
BOOL found = ( index <= 0 | FALSE | hay stack[index]=needle);
print(("""", needle, """ ", (found|"FOUND at"|"near"), " index ", whole(index, 0), newline))
OD;
test search(iterative binary search, test cases);
test search(recursive binary search, test cases)
)
END

View file

@ -0,0 +1,49 @@
begin % binary search %
% recursive binary search, left most insertion point %
integer procedure binarySearchLR ( integer array A ( * )
; integer value find, Low, high
) ;
if high < low then low
else begin
integer mid;
mid := ( low + high ) div 2;
if A( mid ) >= find then binarySearchLR( A, find, low, mid - 1 )
else binarySearchLR( A, find, mid + 1, high )
end binarySearchR ;
% iteratve binary search leftmost insertion point %
integer procedure binarySearchLI ( integer array A ( * )
; integer value find, lowInit, highInit
) ;
begin
integer low, high;
low := lowInit;
high := highInit;
while low <= high do begin
integer mid;
mid := ( low + high ) div 2;
if A( mid ) >= find then high := mid - 1
else low := mid + 1
end while_low_le_high ;
low
end binarySearchLI ;
% tests %
begin
integer array t ( 1 :: 10 );
integer tPos;
tPos := 1;
for tValue := 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 do begin
t( tPos ) := tValue;
tPos := tPOs + 1
end for_tValue ;
for s := 0 step 8 until 24 do begin
integer pos;
pos := binarySearchLR( t, s, 1, 10 );
if t( pos ) = s then write( I_W := 3, S_W := 0, "recursive search finds ", s, " at ", pos )
else write( I_W := 3, S_W := 0, "recursive search suggests insert ", s, " at ", pos )
;
pos := binarySearchLI( t, s, 1, 10 );
if t( pos ) = s then write( I_W := 3, S_W := 0, "iterative search finds ", s, " at ", pos )
else write( I_W := 3, S_W := 0, "iterative search suggests insert ", s, " at ", pos )
end for_s
end
end.

View file

@ -0,0 +1,9 @@
binsrch{
⎕IO({ ⍝ first lower bound is start of array
<: ⍝ if high < low, we didn't find it
mid(+)÷2 ⍝ calculate mid point
[mid]>:mid-1 ⍝ if too high, search from to mid-1
[mid]<:(mid+1) ⍝ if too low, search from mid+1 to ⍵
mid ⍝ otherwise, we did find it
})⎕IO+()-1 ⍝ first higher bound is top of array
}

View file

@ -0,0 +1,274 @@
/* ARM assembly Raspberry PI */
/* program binsearch.s */
/************************************/
/* Constantes */
/************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResult: .ascii "Value find at index : "
sMessValeur: .fill 11, 1, ' ' @ size => 11
szCarriageReturn: .asciz "\n"
sMessRecursif: .asciz "Recursive search : \n"
sMessNotFound: .asciz "Value not found. \n"
.equ NBELEMENTS, 9
TableNumber: .int 4,6,7,10,11,15,22,30,35
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
mov r0,#4 @ search first value
ldr r1,iAdrTableNumber @ address number table
mov r2,#NBELEMENTS @ number of élements
bl bSearch
ldr r1,iAdrsMessValeur @ display value
bl conversion10 @ call function
ldr r0,iAdrsMessResult
bl affichageMess @ display message
mov r0,#11 @ search median value
ldr r1,iAdrTableNumber
mov r2,#NBELEMENTS
bl bSearch
ldr r1,iAdrsMessValeur @ display value
bl conversion10 @ call function
ldr r0,iAdrsMessResult
bl affichageMess @ display message
mov r0,#12 @value not found
ldr r1,iAdrTableNumber
mov r2,#NBELEMENTS
bl bSearch
cmp r0,#-1
bne 2f
ldr r0,iAdrsMessNotFound
bl affichageMess
b 3f
2:
ldr r1,iAdrsMessValeur @ display value
bl conversion10 @ call function
ldr r0,iAdrsMessResult
bl affichageMess @ display message
3:
mov r0,#35 @ search last value
ldr r1,iAdrTableNumber
mov r2,#NBELEMENTS
bl bSearch
ldr r1,iAdrsMessValeur @ display value
bl conversion10 @ call function
ldr r0,iAdrsMessResult
bl affichageMess @ display message
/****************************************/
/* recursive */
/****************************************/
ldr r0,iAdrsMessRecursif
bl affichageMess @ display message
mov r0,#4 @ search first value
ldr r1,iAdrTableNumber
mov r2,#0 @ low index of elements
mov r3,#NBELEMENTS - 1 @ high index of elements
bl bSearchR
ldr r1,iAdrsMessValeur @ display value
bl conversion10 @ call function
ldr r0,iAdrsMessResult
bl affichageMess @ display message
mov r0,#11
ldr r1,iAdrTableNumber
mov r2,#0
mov r3,#NBELEMENTS - 1
bl bSearchR
ldr r1,iAdrsMessValeur @ display value
bl conversion10 @ call function
ldr r0,iAdrsMessResult
bl affichageMess @ display message
mov r0,#12
ldr r1,iAdrTableNumber
mov r2,#0
mov r3,#NBELEMENTS - 1
bl bSearchR
cmp r0,#-1
bne 2f
ldr r0,iAdrsMessNotFound
bl affichageMess
b 3f
2:
ldr r1,iAdrsMessValeur @ display value
bl conversion10 @ call function
ldr r0,iAdrsMessResult
bl affichageMess @ display message
3:
mov r0,#35
ldr r1,iAdrTableNumber
mov r2,#0
mov r3,#NBELEMENTS - 1
bl bSearchR
ldr r1,iAdrsMessValeur @ display value
bl conversion10 @ call function
ldr r0,iAdrsMessResult
bl affichageMess @ display message
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrsMessValeur: .int sMessValeur
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsMessResult: .int sMessResult
iAdrsMessRecursif: .int sMessRecursif
iAdrsMessNotFound: .int sMessNotFound
iAdrTableNumber: .int TableNumber
/******************************************************************/
/* binary search iterative */
/******************************************************************/
/* r0 contains the value to search */
/* r1 contains the adress of table */
/* r2 contains the number of elements */
/* r0 return index or -1 if not find */
bSearch:
push {r2-r5,lr} @ save registers
mov r3,#0 @ low index
sub r4,r2,#1 @ high index = number of elements - 1
1:
cmp r3,r4
movgt r0,#-1 @not found
bgt 100f
add r2,r3,r4 @ compute (low + high) /2
lsr r2,#1
ldr r5,[r1,r2,lsl #2] @ load value of table at index r2
cmp r5,r0
moveq r0,r2 @ find !!!
beq 100f
addlt r3,r2,#1 @ lower -> index low = index + 1
subgt r4,r2,#1 @ bigger -> index high = index - 1
b 1b @ and loop
100:
pop {r2-r5,lr}
bx lr @ return
/******************************************************************/
/* binary search recursif */
/******************************************************************/
/* r0 contains the value to search */
/* r1 contains the adress of table */
/* r2 contains the low index of elements */
/* r3 contains the high index of elements */
/* r0 return index or -1 if not find */
bSearchR:
push {r2-r5,lr} @ save registers
cmp r3,r2 @ index high < low ?
movlt r0,#-1 @ yes -> not found
blt 100f
add r4,r2,r3 @ compute (low + high) /2
lsr r4,#1
ldr r5,[r1,r4,lsl #2] @ load value of table at index r4
cmp r5,r0
moveq r0,r4 @ find !!!
beq 100f
bgt 1f @ bigger ?
add r2,r4,#1 @ no new search with low = index + 1
bl bSearchR
b 100f
1: @ bigger
sub r3,r4,#1 @ new search with high = index - 1
bl bSearchR
100:
pop {r2-r5,lr}
bx lr @ return
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur des 2 registres
bx lr @ return
/******************************************************************/
/* Converting a register to a decimal unsigned */
/******************************************************************/
/* r0 contains value and r1 address area */
/* r0 return size of result (no zero final in area) */
/* area size => 11 bytes */
.equ LGZONECAL, 10
conversion10:
push {r1-r4,lr} @ save registers
mov r3,r1
mov r2,#LGZONECAL
1: @ start loop
bl divisionpar10U @unsigned r0 <- dividende. quotient ->r0 reste -> r1
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
cmp r0,#0 @ stop if quotient = 0
subne r2,#1 @ else previous position
bne 1b @ and loop
@ and move digit from left of area
mov r4,#0
2:
ldrb r1,[r3,r2]
strb r1,[r3,r4]
add r2,#1
add r4,#1
cmp r2,#LGZONECAL
ble 2b
@ and move spaces in end on area
mov r0,r4 @ result length
mov r1,#' ' @ space
3:
strb r1,[r3,r4] @ store space in area
add r4,#1 @ next position
cmp r4,#LGZONECAL
ble 3b @ loop if r4 <= area size
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
/***************************************************/
/* division par 10 unsigned */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10U:
push {r2,r3,r4, lr}
mov r4,r0 @ save value
//mov r3,#0xCCCD @ r3 <- magic_number lower raspberry 3
//movt r3,#0xCCCC @ r3 <- magic_number higter raspberry 3
ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2
umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)
mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)
pop {r2,r3,r4,lr}
bx lr @ leave function
iMagicNumber: .int 0xCCCCCCCD

View file

@ -0,0 +1,60 @@
REM Binary search
DIM A(10)
REM Sorted data
DATA -31, 0, 1, 2, 2, 4, 65, 83, 99, 782
FOR I = 0 TO 9
READ A(I)
NEXT I
N = 10
X = 2
GOSUB DoBinarySearch:
GOSUB PrintResult:
X = 5
GOSUB DoBinarySearch:
GOSUB PrintResult:
END
PrintResult:
PRINT X;
IF IndX >= 0 THEN
PRINT " is at index ";
PRINT IndX;
PRINT "."
ELSE
PRINT " is not found."
ENDIF
RETURN
DoBinarySearch:
REM Binary search algorithm
REM N - number of elements
REM X - searched element
REM Result: IndX - index of X
L = 0
H = N - 1
Found = 0
Loop:
IF L > H THEN AfterLoop:
IF Found <> 0 THEN AfterLoop:
REM (L <= H) and (Found = 0)
M = H - L
M = M / 2
M = L + M
REM So, M = L + (H - L) / 2
IF A(M) < X THEN
L = M + 1
ELSE
IF A(M) > X THEN
H = M - 1
ELSE
Found = 1
ENDIF
ENDIF
GOTO Loop:
AfterLoop:
IF Found = 0 THEN
IndX = -1
ELSE
IndX = M
ENDIF
RETURN

View file

@ -0,0 +1,8 @@
function binary_search(array, value, left, right, middle) {
if (right < left) return 0
middle = int((right + left) / 2)
if (value == array[middle]) return 1
if (value < array[middle])
return binary_search(array, value, left, middle - 1)
return binary_search(array, value, middle + 1, right)
}

View file

@ -0,0 +1,9 @@
function binary_search(array, value, left, right, middle) {
while (left <= right) {
middle = int((right + left) / 2)
if (value == array[middle]) return 1
if (value < array[middle]) right = middle - 1
else left = middle + 1
}
return 0
}

View file

@ -0,0 +1,46 @@
INT FUNC BinarySearch(INT ARRAY a INT len,value)
INT low,high,mid
low=0 high=len-1
WHILE low<=high
DO
mid=low+(high-low) RSH 1
IF a(mid)>value THEN
high=mid-1
ELSEIF a(mid)<value THEN
low=mid+1
ELSE
RETURN (mid)
FI
OD
RETURN (-1)
PROC Test(INT ARRAY a INT len,value)
INT i
Put('[)
FOR i=0 TO len-1
DO
PrintI(a(i))
IF i<len-1 THEN Put(32) FI
OD
i=BinarySearch(a,len,value)
Print("] ") PrintI(value)
IF i<0 THEN
PrintE(" not found")
ELSE
Print(" found at index ")
PrintIE(i)
FI
RETURN
PROC Main()
INT ARRAY a=[65530 0 1 2 5 6 8 9]
Test(a,8,6)
Test(a,8,-6)
Test(a,8,9)
Test(a,8,-10)
Test(a,8,10)
Test(a,8,7)
RETURN

View file

@ -0,0 +1,54 @@
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Recursive_Binary_Search is
Not_Found : exception;
generic
type Index is range <>;
type Element is private;
type Array_Of_Elements is array (Index range <>) of Element;
with function "<" (L, R : Element) return Boolean is <>;
function Search (Container : Array_Of_Elements; Value : Element) return Index;
function Search (Container : Array_Of_Elements; Value : Element) return Index is
Mid : Index;
begin
if Container'Length > 0 then
Mid := (Container'First + Container'Last) / 2;
if Value < Container (Mid) then
if Container'First /= Mid then
return Search (Container (Container'First..Mid - 1), Value);
end if;
elsif Container (Mid) < Value then
if Container'Last /= Mid then
return Search (Container (Mid + 1..Container'Last), Value);
end if;
else
return Mid;
end if;
end if;
raise Not_Found;
end Search;
type Integer_Array is array (Positive range <>) of Integer;
function Find is new Search (Positive, Integer, Integer_Array);
procedure Test (X : Integer_Array; E : Integer) is
begin
New_Line;
for I in X'Range loop
Put (Integer'Image (X (I)));
end loop;
Put (" contains" & Integer'Image (E) & " at" & Integer'Image (Find (X, E)));
exception
when Not_Found =>
Put (" does not contain" & Integer'Image (E));
end Test;
begin
Test ((2, 4, 6, 8, 9), 2);
Test ((2, 4, 6, 8, 9), 1);
Test ((2, 4, 6, 8, 9), 8);
Test ((2, 4, 6, 8, 9), 10);
Test ((2, 4, 6, 8, 9), 9);
Test ((2, 4, 6, 8, 9), 5);
end Test_Recursive_Binary_Search;

View file

@ -0,0 +1,56 @@
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Binary_Search is
Not_Found : exception;
generic
type Index is range <>;
type Element is private;
type Array_Of_Elements is array (Index range <>) of Element;
with function "<" (L, R : Element) return Boolean is <>;
function Search (Container : Array_Of_Elements; Value : Element) return Index;
function Search (Container : Array_Of_Elements; Value : Element) return Index is
Low : Index := Container'First;
High : Index := Container'Last;
Mid : Index;
begin
if Container'Length > 0 then
loop
Mid := (Low + High) / 2;
if Value < Container (Mid) then
exit when Low = Mid;
High := Mid - 1;
elsif Container (Mid) < Value then
exit when High = Mid;
Low := Mid + 1;
else
return Mid;
end if;
end loop;
end if;
raise Not_Found;
end Search;
type Integer_Array is array (Positive range <>) of Integer;
function Find is new Search (Positive, Integer, Integer_Array);
procedure Test (X : Integer_Array; E : Integer) is
begin
New_Line;
for I in X'Range loop
Put (Integer'Image (X (I)));
end loop;
Put (" contains" & Integer'Image (E) & " at" & Integer'Image (Find (X, E)));
exception
when Not_Found =>
Put (" does not contain" & Integer'Image (E));
end Test;
begin
Test ((2, 4, 6, 8, 9), 2);
Test ((2, 4, 6, 8, 9), 1);
Test ((2, 4, 6, 8, 9), 8);
Test ((2, 4, 6, 8, 9), 10);
Test ((2, 4, 6, 8, 9), 9);
Test ((2, 4, 6, 8, 9), 5);
end Test_Binary_Search;

View file

@ -0,0 +1,25 @@
on binarySearch(n, theList, l, r)
repeat until (l = r)
set m to (l + r) div 2
if (item m of theList < n) then
set l to m + 1
else
set r to m
end if
end repeat
if (item l of theList is n) then return l
return missing value
end binarySearch
on test(n, theList, l, r)
set |result| to binarySearch(n, theList, l, r)
if (|result| is missing value) then
return (n as text) & " is not in range " & l & " thru " & r & " of the list"
else
return "The first occurrence of " & n & " in range " & l & " thru " & r & " of the list is at index " & |result|
end if
end test
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)

View file

@ -0,0 +1,49 @@
100 REM Binary search
110 HOME : REM 110 CLS for Chipmunk Basic, MSX Basic, QBAsic and Quite BASIC
111 REM REMOVE line 110 for Minimal BASIC
120 DIM a(10)
130 LET n = 10
140 FOR j = 1 TO n
150 READ a(j)
160 NEXT j
170 REM Sorted data
180 DATA -31,0,1,2,2,4,65,83,99,782
190 LET x = 2
200 GOSUB 440
210 GOSUB 310
220 LET x = 5
230 GOSUB 440
240 GOSUB 310
250 GOTO 720
300 REM Print result
310 PRINT x;
320 IF i < 0 THEN 350
330 PRINT " is at index "; i; "."
340 RETURN
350 PRINT " is not found."
360 RETURN
400 REM Binary search algorithm
410 REM N - number of elements
420 REM X - searched element
430 REM Result: I - index of X
440 LET l = 0
450 LET h = n - 1
460 LET f = 0
470 LET m = l
480 IF l > h THEN 590
490 IF f <> 0 THEN 590
500 LET m = l + INT((h - l) / 2)
510 IF a(m) >= x THEN 540
520 LET l = m + 1
530 GOTO 480
540 IF a(m) <= x THEN 570
550 LET h = m - 1
560 GOTO 480
570 LET f = 1
580 GOTO 480
590 IF f = 0 THEN 700
600 LET i = m
610 RETURN
700 LET i = -1
710 RETURN
720 END

View file

@ -0,0 +1,20 @@
binarySearch: function [arr,val,low,high][
if high < low -> return ø
mid: shr low+high 1
case [val]
when? [< arr\[mid]] -> return binarySearch arr val low mid-1
when? [> arr\[mid]] -> return binarySearch arr val mid+1 high
else -> return mid
]
ary: [
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
]
loop [0 42 45 24324 99999] 'v [
i: binarySearch ary v 0 (size ary)-1
if? not? null? i -> print ["found" v "at index:" i]
else -> print [v "not found"]
]

View file

@ -0,0 +1,33 @@
array := "1,2,4,6,8,9"
StringSplit, A, array, `, ; creates associative array
MsgBox % x := BinarySearch(A, 4, 1, A0) ; Recursive
MsgBox % A%x%
MsgBox % x := BinarySearchI(A, A0, 4) ; Iterative
MsgBox % A%x%
BinarySearch(A, value, low, high) { ; A0 contains length of array
If (high < low) ; A1, A2, A3...An are array elements
Return not_found
mid := Floor((low + high) / 2)
If (A%mid% > value) ; A%mid% is automatically global since no such locals are present
Return BinarySearch(A, value, low, mid - 1)
Else If (A%mid% < value)
Return BinarySearch(A, value, mid + 1, high)
Else
Return mid
}
BinarySearchI(A, lengthA, value) {
low := 0
high := lengthA - 1
While (low <= high) {
mid := Floor((low + high) / 2) ; round to lower integer
If (A%mid% > value)
high := mid - 1
Else If (A%mid% < value)
low := mid + 1
Else
Return mid
}
Return not_found
}

View file

@ -0,0 +1,16 @@
Lbl BSEARCH
0→L
r₃-1→H
While L≤H
(L+H)/2→M
If {L+M}>r₂
M-1→H
ElseIf {L+M}<r₂
M+1→L
Else
M
Return
End
End
-1
Return

View file

@ -0,0 +1,17 @@
FUNCTION binary_search ( array() AS Integer, value AS Integer, lo AS Integer, hi AS Integer) AS Integer
DIM middle AS Integer
IF hi < lo THEN
binary_search = 0
ELSE
middle = (hi + lo) / 2
SELECT CASE value
CASE IS < array(middle)
binary_search = binary_search(array(), value, lo, middle-1)
CASE IS > array(middle)
binary_search = binary_search(array(), value, middle+1, hi)
CASE ELSE
binary_search = middle
END SELECT
END IF
END FUNCTION

View file

@ -0,0 +1,17 @@
FUNCTION binary_search ( array() AS Integer, value AS Integer, lo AS Integer, hi AS Integer) AS Integer
DIM middle AS Integer
WHILE lo <= hi
middle = (hi + lo) / 2
SELECT CASE value
CASE IS < array(middle)
hi = middle - 1
CASE IS > array(middle)
lo = middle + 1
CASE ELSE
binary_search = middle
EXIT FUNCTION
END SELECT
WEND
binary_search = 0
END FUNCTION

View file

@ -0,0 +1,23 @@
SUB search (array() AS Integer, value AS Integer)
DIM idx AS Integer
idx = binary_search(array(), value, LBOUND(array), UBOUND(array))
PRINT "Value "; value;
IF idx < 1 THEN
PRINT " not found"
ELSE
PRINT " found at index "; idx
END IF
END SUB
DIM test(1 TO 10) AS Integer
DIM i AS Integer
DATA 2, 3, 5, 6, 8, 10, 11, 15, 19, 20
FOR i = 1 TO 10 ' Fill the test array
READ test(i)
NEXT i
search test(), 4
search test(), 8
search test(), 20

View file

@ -0,0 +1,10 @@
function binarySearchR(array, valor, lb, ub)
if ub < lb then
return false
else
mitad = floor((lb + ub) / 2)
if valor < array[mitad] then return binarySearchR(array, valor, lb, mitad-1)
if valor > array[mitad] then return binarySearchR(array, valor, mitad+1, ub)
if valor = array[mitad] then return mitad
end if
end function

View file

@ -0,0 +1,17 @@
function binarySearchI(array, valor)
lb = array[?,]
ub = array[?]
while lb <= ub
mitad = floor((lb + ub) / 2)
begin case
case array[mitad] > valor
ub = mitad - 1
case array[mitad] < valor
lb = mitad + 1
else
return mitad
end case
end while
return false
end function

View file

@ -0,0 +1,11 @@
items = 10e5
dim array(items)
for n = 0 to items-1 : array[n] = n : next n
t0 = msec
print binarySearchI(array, 3)
print msec - t0; " millisec"
t1 = msec
print binarySearchR(array, 3, array[?,], array[?])
print msec - t1; " millisec"
end

View file

@ -0,0 +1,23 @@
DIM array%(9)
array%() = 7, 14, 21, 28, 35, 42, 49, 56, 63, 70
secret% = 42
index% = FNwhere(array%(), secret%, 0, DIM(array%(),1))
IF index% >= 0 THEN
PRINT "The value "; secret% " was found at index "; index%
ELSE
PRINT "The value "; secret% " was not found"
ENDIF
END
REM Search ordered array A%() for the value S% from index B% to T%
DEF FNwhere(A%(), S%, B%, T%)
LOCAL H%
H% = 2
WHILE H%<(T%-B%) H% *= 2:ENDWHILE
H% /= 2
REPEAT
IF (B%+H%)<=T% IF S%>=A%(B%+H%) B% += H%
H% /= 2
UNTIL H%=0
IF S%=A%(B%) THEN = B% ELSE = -1

View file

@ -0,0 +1,14 @@
BSearch {
BS a, value:
BS a, value, 0, ¯1+a;
BS a, value, low, high:
mid 2÷˜low+high
{
high<low ? ¯1;
(mida)>value ? BS a, value, low, mid-1;
(mida)<value ? BS a, value, mid+1, high;
mid
}
}
•Show BSearch 8303545497779828797, 97

View file

@ -0,0 +1 @@
9

View file

@ -0,0 +1,48 @@
@echo off & setlocal enabledelayedexpansion
:: Binary Chop Algorithm - Michael Sanders 2017
::
:: example output...
::
:: binary chop algorithm vs. standard for loop
::
:: number to find 941
:: for loop required 941 iterations
:: binchop required 10 iterations
:setup
set x=1
set y=999
set /a z=(%random% * (%y% - 1) / 32768 + 1)
:pseudoarray
for /l %%q in (%x%,1,%y%) do set /a array[%%q]=%%q
:std4loop
for /l %%q in (%x%,1,%y%) do (
if !array[%%q]!==%z% (set f=%%q& goto :binchop)
)
:binchop
if !x! leq !y! (
set /a i+=1
set /a "p=(!x!+!y!)/2"
call set /a t=%%array[!p!]%%
if !t! equ !z! (set b=!i!& goto :done)
if !t! lss !z! (set /a x=!p!+1) else (set /a y=!p!-1)
goto :binchop
)
:done
cls
echo binary chop algorithm vs. standard for loop...
echo.
echo . number to find !z!
echo . for loop required !f! iterations
echo . binchop required !b! iterations
endlocal & exit /b 0

View file

@ -0,0 +1,31 @@
binary_search = { search_array, value, low, high |
true? high < low
{ null }
{
mid = ((low + high) / 2).to_i
true? search_array[mid] > value
{ binary_search search_array, value, low, mid - 1 }
{ true? search_array[mid] < value
{ binary_search search_array, value, mid + 1, high }
{ mid }
}
}
}
#Populate array
numbers = 1000.of { random 1000 }
#Sort the array
numbers.sort!
#Find a number
x = random 1000
p "Looking for #{x}"
index = binary_search numbers, x, 0, numbers.length - 1
null? index
{ p "Not found" }
{ p "Found at index: #{index}" }

View file

@ -0,0 +1,26 @@
template <class T> int binsearch(const T array[], int low, int high, T value) {
if (high < low) {
return -1;
}
auto mid = (low + high) / 2;
if (value < array[mid]) {
return binsearch(array, low, mid - 1, value);
} else if (value > array[mid]) {
return binsearch(array, mid + 1, high, value);
}
return mid;
}
#include <iostream>
int main()
{
int array[] = {2, 3, 5, 6, 8};
int result1 = binsearch(array, 0, sizeof(array)/sizeof(int), 4),
result2 = binsearch(array, 0, sizeof(array)/sizeof(int), 8);
if (result1 == -1) std::cout << "4 not found!" << std::endl;
else std::cout << "4 found at " << result1 << std::endl;
if (result2 == -1) std::cout << "8 not found!" << std::endl;
else std::cout << "8 found at " << result2 << std::endl;
return 0;
}

View file

@ -0,0 +1,15 @@
template <class T>
int binSearch(const T arr[], int len, T what) {
int low = 0;
int high = len - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] > what)
high = mid - 1;
else if (arr[mid] < what)
low = mid + 1;
else
return mid;
}
return -1; // indicate not found
}

View file

@ -0,0 +1 @@
#include <algorithm>

View file

@ -0,0 +1 @@
int *ptr = std::lower_bound(array, array+len, what); // a custom comparator can be given as fourth arg

View file

@ -0,0 +1 @@
int *ptr = std::upper_bound(array, array+len, what); // a custom comparator can be given as fourth arg

View file

@ -0,0 +1 @@
std::pair<int *, int *> bounds = std::equal_range(array, array+len, what); // a custom comparator can be given as fourth arg

View file

@ -0,0 +1 @@
bool found = std::binary_search(array, array+len, what); // a custom comparator can be given as fourth arg

View file

@ -0,0 +1,71 @@
namespace Search {
using System;
public static partial class Extensions {
/// <summary>Use Binary Search to find index of GLB for value</summary>
/// <typeparam name="T">type of entries and value</typeparam>
/// <param name="entries">array of entries</param>
/// <param name="value">search value</param>
/// <remarks>entries must be in ascending order</remarks>
/// <returns>index into entries of GLB for value</returns>
public static int RecursiveBinarySearchForGLB<T>(this T[] entries, T value)
where T : IComparable {
return entries.RecursiveBinarySearchForGLB(value, 0, entries.Length - 1);
}
/// <summary>Use Binary Search to find index of GLB for value</summary>
/// <typeparam name="T">type of entries and value</typeparam>
/// <param name="entries">array of entries</param>
/// <param name="value">search value</param>
/// <param name="left">leftmost index to search</param>
/// <param name="right">rightmost index to search</param>
/// <remarks>entries must be in ascending order</remarks>
/// <returns>index into entries of GLB for value</returns>
public static int RecursiveBinarySearchForGLB<T>(this T[] entries, T value, int left, int right)
where T : IComparable {
if (left <= right) {
var middle = left + (right - left) / 2;
return entries[middle].CompareTo(value) < 0 ?
entries.RecursiveBinarySearchForGLB(value, middle + 1, right) :
entries.RecursiveBinarySearchForGLB(value, left, middle - 1);
}
//[Assert]left == right + 1
// GLB: entries[right] < value && value <= entries[right + 1]
return right;
}
/// <summary>Use Binary Search to find index of LUB for value</summary>
/// <typeparam name="T">type of entries and value</typeparam>
/// <param name="entries">array of entries</param>
/// <param name="value">search value</param>
/// <remarks>entries must be in ascending order</remarks>
/// <returns>index into entries of LUB for value</returns>
public static int RecursiveBinarySearchForLUB<T>(this T[] entries, T value)
where T : IComparable {
return entries.RecursiveBinarySearchForLUB(value, 0, entries.Length - 1);
}
/// <summary>Use Binary Search to find index of LUB for value</summary>
/// <typeparam name="T">type of entries and value</typeparam>
/// <param name="entries">array of entries</param>
/// <param name="value">search value</param>
/// <param name="left">leftmost index to search</param>
/// <param name="right">rightmost index to search</param>
/// <remarks>entries must be in ascending order</remarks>
/// <returns>index into entries of LUB for value</returns>
public static int RecursiveBinarySearchForLUB<T>(this T[] entries, T value, int left, int right)
where T : IComparable {
if (left <= right) {
var middle = left + (right - left) / 2;
return entries[middle].CompareTo(value) <= 0 ?
entries.RecursiveBinarySearchForLUB(value, middle + 1, right) :
entries.RecursiveBinarySearchForLUB(value, left, middle - 1);
}
//[Assert]left == right + 1
// LUB: entries[left] > value && value >= entries[left - 1]
return left;
}
}
}

View file

@ -0,0 +1,73 @@
namespace Search {
using System;
public static partial class Extensions {
/// <summary>Use Binary Search to find index of GLB for value</summary>
/// <typeparam name="T">type of entries and value</typeparam>
/// <param name="entries">array of entries</param>
/// <param name="value">search value</param>
/// <remarks>entries must be in ascending order</remarks>
/// <returns>index into entries of GLB for value</returns>
public static int BinarySearchForGLB<T>(this T[] entries, T value)
where T : IComparable {
return entries.BinarySearchForGLB(value, 0, entries.Length - 1);
}
/// <summary>Use Binary Search to find index of GLB for value</summary>
/// <typeparam name="T">type of entries and value</typeparam>
/// <param name="entries">array of entries</param>
/// <param name="value">search value</param>
/// <param name="left">leftmost index to search</param>
/// <param name="right">rightmost index to search</param>
/// <remarks>entries must be in ascending order</remarks>
/// <returns>index into entries of GLB for value</returns>
public static int BinarySearchForGLB<T>(this T[] entries, T value, int left, int right)
where T : IComparable {
while (left <= right) {
var middle = left + (right - left) / 2;
if (entries[middle].CompareTo(value) < 0)
left = middle + 1;
else
right = middle - 1;
}
//[Assert]left == right + 1
// GLB: entries[right] < value && value <= entries[right + 1]
return right;
}
/// <summary>Use Binary Search to find index of LUB for value</summary>
/// <typeparam name="T">type of entries and value</typeparam>
/// <param name="entries">array of entries</param>
/// <param name="value">search value</param>
/// <remarks>entries must be in ascending order</remarks>
/// <returns>index into entries of LUB for value</returns>
public static int BinarySearchForLUB<T>(this T[] entries, T value)
where T : IComparable {
return entries.BinarySearchForLUB(value, 0, entries.Length - 1);
}
/// <summary>Use Binary Search to find index of LUB for value</summary>
/// <typeparam name="T">type of entries and value</typeparam>
/// <param name="entries">array of entries</param>
/// <param name="value">search value</param>
/// <param name="left">leftmost index to search</param>
/// <param name="right">rightmost index to search</param>
/// <remarks>entries must be in ascending order</remarks>
/// <returns>index into entries of LUB for value</returns>
public static int BinarySearchForLUB<T>(this T[] entries, T value, int left, int right)
where T : IComparable {
while (left <= right) {
var middle = left + (right - left) / 2;
if (entries[middle].CompareTo(value) <= 0)
left = middle + 1;
else
right = middle - 1;
}
//[Assert]left == right + 1
// LUB: entries[left] > value && value >= entries[left - 1]
return left;
}
}
}

View file

@ -0,0 +1,43 @@
//#define UseRecursiveSearch
using System;
using Search;
class Program {
static readonly int[][] tests = {
new int[] { },
new int[] { 2 },
new int[] { 2, 2 },
new int[] { 2, 2, 2, 2 },
new int[] { 3, 3, 4, 4 },
new int[] { 0, 1, 3, 3, 4, 4 },
new int[] { 0, 1, 2, 2, 2, 3, 3, 4, 4},
new int[] { 0, 1, 1, 2, 2, 2, 3, 3, 4, 4 },
new int[] { 0, 1, 1, 1, 1, 2, 2, 3, 3, 4, 4 },
new int[] { 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4 },
new int[] { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4 },
};
static void Main(string[] args) {
var index = 0;
foreach (var test in tests) {
var join = String.Join(" ", test);
Console.WriteLine($"test[{index}]: {join}");
#if UseRecursiveSearch
var glb = test.RecursiveBinarySearchForGLB(2);
var lub = test.RecursiveBinarySearchForLUB(2);
#else
var glb = test.BinarySearchForGLB(2);
var lub = test.BinarySearchForLUB(2);
#endif
Console.WriteLine($"glb = {glb}");
Console.WriteLine($"lub = {lub}");
index++;
}
#if DEBUG
Console.Write("Press Enter");
Console.ReadLine();
#endif
}
}

View file

@ -0,0 +1,52 @@
#include <stdio.h>
int bsearch (int *a, int n, int x) {
int i = 0, j = n - 1;
while (i <= j) {
int k = i + ((j - i) / 2);
if (a[k] == x) {
return k;
}
else if (a[k] < x) {
i = k + 1;
}
else {
j = k - 1;
}
}
return -1;
}
int bsearch_r (int *a, int x, int i, int j) {
if (j < i) {
return -1;
}
int k = i + ((j - i) / 2);
if (a[k] == x) {
return k;
}
else if (a[k] < x) {
return bsearch_r(a, x, k + 1, j);
}
else {
return bsearch_r(a, x, i, k - 1);
}
}
int main () {
int a[] = {-31, 0, 1, 2, 2, 4, 65, 83, 99, 782};
int n = sizeof a / sizeof a[0];
int x = 2;
int i = bsearch(a, n, x);
if (i >= 0)
printf("%d is at index %d.\n", x, i);
else
printf("%d is not found.\n", x);
x = 5;
i = bsearch_r(a, x, 0, n - 1);
if (i >= 0)
printf("%d is at index %d.\n", x, i);
else
printf("%d is not found.\n", x);
return 0;
}

View file

@ -0,0 +1,47 @@
% Binary search in an array
% If the item is found, returns `true' and the index;
% if the item is not found, returns `false' and the leftmost insertion point
% The datatype must support the < and > operators.
binary_search = proc [T: type] (a: array[T], val: T) returns (bool, int)
where T has lt: proctype (T,T) returns (bool),
T has gt: proctype (T,T) returns (bool)
low: int := array[T]$low(a)
high: int := array[T]$high(a)
while low <= high do
mid: int := low + (high - low) / 2
if a[mid] > val then
high := mid - 1
elseif a[mid] < val then
low := mid + 1
else
return (true, mid)
end
end
return (false, low)
end binary_search
% Test the binary search on an array
start_up = proc ()
po: stream := stream$primary_output()
% primes up to 20 (note that arrays are 1-indexed by default)
primes: array[int] := array[int]$[2,3,5,7,11,13,17,19]
% binary search for each number from 1 to 20
for n: int in int$from_to(1,20) do
i: int
found: bool
found, i := binary_search[int](primes, n)
if found then
stream$putl(po, int$unparse(n)
|| " found at location "
|| int$unparse(i));
else
stream$putl(po, int$unparse(n)
|| " not found, would be inserted at location "
|| int$unparse(i));
end
end
end start_up

View file

@ -0,0 +1,18 @@
>>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. binary-search.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 nums-area VALUE "01040612184356".
03 nums PIC 9(2)
OCCURS 7 TIMES
ASCENDING KEY nums
INDEXED BY nums-idx.
PROCEDURE DIVISION.
SEARCH ALL nums
WHEN nums (nums-idx) = 4
DISPLAY "Found 4 at index " nums-idx
END-SEARCH
.
END PROGRAM binary-search.

View file

@ -0,0 +1,17 @@
proc binsearch(A:[], value) {
var low = A.domain.dim(1).low;
var high = A.domain.dim(1).high;
while (low <= high) {
var mid = (low + high) / 2;
if A(mid) > value then
high = mid - 1;
else if A(mid) < value then
low = mid + 1;
else
return mid;
}
return 0;
}
writeln(binsearch([3, 4, 6, 9, 11], 9));

View file

@ -0,0 +1,25 @@
100 rem Binary search
110 cls
120 dim a(10)
130 n% = 10
140 for i% = 0 to 9 : read a(i%) : next i%
150 rem Sorted data
160 data -31,0,1,2,2,4,65,83,99,782
170 x = 2 : gosub 280
180 gosub 230
190 x = 5 : gosub 280
200 gosub 230
210 end
220 rem Print result
230 print x;
240 if indx% >= 0 then print "is at index ";str$(indx%);"." else print "is not found."
250 return
260 rem Binary search algorithm
270 rem N% - number of elements; X - searched element; Result: INDX% - index of X
280 l% = 0 : h% = n%-1 : found% = 0
290 while (l% <= h%) and not found%
300 m% = l%+int((h%-l%)/2)
310 if a(m%) < x then l% = m%+1 else if a(m%) > x then h% = m%-1 else found% = -1
320 wend
330 if found% = 0 then indx% = -1 else indx% = m%
340 return

View file

@ -0,0 +1,16 @@
(defn bsearch
([coll t]
(bsearch coll 0 (dec (count coll)) t))
([coll l u t]
(if (> l u) -1
(let [m (quot (+ l u) 2) mth (nth coll m)]
(cond
; the middle element is greater than t
; so search the lower half
(> mth t) (recur coll l (dec m) t)
; the middle element is less than t
; so search the upper half
(< mth t) (recur coll (inc m) u t)
; we've found our target
; so return its index
(= mth t) m)))))

View file

@ -0,0 +1,8 @@
binarySearch = (xs, x) ->
do recurse = (low = 0, high = xs.length - 1) ->
mid = Math.floor (low + high) / 2
switch
when high < low then NaN
when xs[mid] > x then recurse low, mid - 1
when xs[mid] < x then recurse mid + 1, high
else mid

View file

@ -0,0 +1,9 @@
binarySearch = (xs, x) ->
[low, high] = [0, xs.length - 1]
while low <= high
mid = Math.floor (low + high) / 2
switch
when xs[mid] > x then high = mid - 1
when xs[mid] < x then low = mid + 1
else return mid
NaN

View file

@ -0,0 +1,8 @@
do (n = 12) ->
odds = (it for it in [1..n] by 2)
result = (it for it in \
(binarySearch odds, it for it in [0..n]) \
when not isNaN it)
console.assert "#{result}" is "#{[0...odds.length]}"
console.log "#{odds} are odd natural numbers"
console.log "#{it} is ordinal of #{odds[it]}" for it in result

View file

@ -0,0 +1,14 @@
(defun binary-search (value array)
(let ((low 0)
(high (1- (length array))))
(do () ((< high low) nil)
(let ((middle (floor (+ low high) 2)))
(cond ((> (aref array middle) value)
(setf high (1- middle)))
((< (aref array middle) value)
(setf low (1+ middle)))
(t (return middle)))))))

View file

@ -0,0 +1,12 @@
(defun binary-search (value array &optional (low 0) (high (1- (length array))))
(if (< high low)
nil
(let ((middle (floor (+ low high) 2)))
(cond ((> (aref array middle) value)
(binary-search value array low (1- middle)))
((< (aref array middle) value)
(binary-search value array (1+ middle) high))
(t middle)))))

View file

@ -0,0 +1,77 @@
'iterative binary search example
define size = 0, search = 0, flag = 0, value = 0
define middle = 0, low = 0, high = 0
dim list[2, 3, 5, 6, 8, 10, 11, 15, 19, 20]
arraysize size, list
let value = 4
gosub binarysearch
let value = 8
gosub binarysearch
let value = 20
gosub binarysearch
end
sub binarysearch
let search = 1
let middle = 0
let low = 0
let high = size
do
if low <= high then
let middle = int((high + low ) / 2)
let flag = 1
if value < list[middle] then
let high = middle - 1
let flag = 0
endif
if value > list[middle] then
let low = middle + 1
let flag = 0
endif
if flag = 1 then
let search = 0
endif
endif
loop low <= high and search = 1
if search = 1 then
let middle = 0
endif
if middle < 1 then
print "not found"
endif
if middle >= 1 then
print "found at index ", middle
endif
return

View file

@ -0,0 +1,25 @@
class Array
def binary_search(val, low = 0, high = (size - 1))
return nil if high < low
#mid = (low + high) >> 1
mid = low + ((high - low) >> 1)
case val <=> self[mid]
when -1
binary_search(val, low, mid - 1)
when 1
binary_search(val, mid + 1, high)
else mid
end
end
end
ary = [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]
[0, 42, 45, 24324, 99999].each do |val|
i = ary.binary_search(val)
if i
puts "found #{val} at index #{i}: #{ary[i]}"
else
puts "#{val} not found in array"
end
end

View file

@ -0,0 +1,29 @@
class Array
def binary_search_iterative(val)
low, high = 0, size - 1
while low <= high
#mid = (low + high) >> 1
mid = low + ((high - low) >> 1)
case val <=> self[mid]
when 1
low = mid + 1
when -1
high = mid - 1
else
return mid
end
end
nil
end
end
ary = [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]
[0, 42, 45, 24324, 99999].each do |val|
i = ary.binary_search_iterative(val)
if i
puts "found #{val} at index #{i}: #{ary[i]}"
else
puts "#{val} not found in array"
end
end

View file

@ -0,0 +1,41 @@
import std.stdio, std.array, std.range, std.traits;
/// Recursive.
bool binarySearch(R, T)(/*in*/ R data, in T x) pure nothrow @nogc
if (isRandomAccessRange!R && is(Unqual!T == Unqual!(ElementType!R))) {
if (data.empty)
return false;
immutable i = data.length / 2;
immutable mid = data[i];
if (mid > x)
return data[0 .. i].binarySearch(x);
if (mid < x)
return data[i + 1 .. $].binarySearch(x);
return true;
}
/// Iterative.
bool binarySearchIt(R, T)(/*in*/ R data, in T x) pure nothrow @nogc
if (isRandomAccessRange!R && is(Unqual!T == Unqual!(ElementType!R))) {
while (!data.empty) {
immutable i = data.length / 2;
immutable mid = data[i];
if (mid > x)
data = data[0 .. i];
else if (mid < x)
data = data[i + 1 .. $];
else
return true;
}
return false;
}
void main() {
/*const*/ auto items = [2, 4, 6, 8, 9].assumeSorted;
foreach (const x; [1, 8, 10, 9, 5, 2])
writefln("%2d %5s %5s %5s", x,
items.binarySearch(x),
items.binarySearchIt(x),
// Standard Binary Search:
!items.equalRange(x).empty);
}

View file

@ -0,0 +1,14 @@
/** Returns null if the value is not found. */
def binarySearch(collection, value) {
var low := 0
var high := collection.size() - 1
while (low <= high) {
def mid := (low + high) // 2
def comparison := value.op__cmp(collection[mid])
if (comparison.belowZero()) { high := mid - 1 } \
else if (comparison.aboveZero()) { low := mid + 1 } \
else if (comparison.isZero()) { return mid } \
else { throw("You expect me to binary search with a partial order?") }
}
return null
}

View file

@ -0,0 +1,34 @@
type BinarySearch:Recursive
fun binarySearch = int by List values, int value
fun recurse = int by int low, int high
if high < low do return -1 end
int mid = low + (high - low) / 2
return when(values[mid] > value,
recurse(low, mid - 1),
when(values[mid] < value,
recurse(mid + 1, high),
mid))
end
return recurse(0, values.length - 1)
end
type BinarySearch:Iterative
fun binarySearch = int by List values, int value
int low = 0
int high = values.length - 1
while low <= high
int mid = low + (high - low) / 2
if values[mid] > value do high = mid - 1
else if values[mid] < value do low = mid + 1
else do return mid
end
end
return -1
end
List values = int[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]
List matches = int[24324, 32, 78, 287, 0, 42, 45, 99999]
for each int match in matches
writeLine("index is: " +
BinarySearch:Recursive.binarySearch(values, match) + ", " +
BinarySearch:Iterative.binarySearch(values, match))
end

View file

@ -0,0 +1,18 @@
proc bin_search val . a[] res .
low = 1
high = len a[]
res = 0
while low <= high and res = 0
mid = (low + high) div 2
if a[mid] > val
high = mid - 1
elif a[mid] < val
low = mid + 1
else
res = mid
.
.
.
a[] = [ 2 4 6 8 9 ]
call bin_search 8 a[] r
print r

View file

@ -0,0 +1,120 @@
class
APPLICATION
create
make
feature {NONE} -- Initialization
make
local
a: ARRAY [INTEGER]
keys: ARRAY [INTEGER]
do
a := <<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>>
keys := <<0, 42, 45, 24324, 99999>>
across keys as k loop
if has_binary (a, k.item) then
print ("The array has an element " + k.item.out)
else
print ("The array has NOT an element " + k.item.out)
end
print ("%N")
end
end
feature -- Search
has_binary (a: ARRAY [INTEGER]; key: INTEGER): BOOLEAN
-- Does `a[a.lower..a.upper]' include an element `key'?
require
is_sorted (a, a.lower, a.upper)
local
i: INTEGER
do
i := where_binary (a, key)
if a.lower <= i and i <= a.upper then
Result := True
else
Result := False
end
end
where_binary (a: ARRAY [INTEGER]; key: INTEGER): INTEGER
-- The index of an element `key' within `a[a.lower..a.upper]' if it exists.
-- Otherwise an integer outside `[a.lower..a.upper]'
require
is_sorted (a, a.lower, a.upper)
do
Result := where_binary_range (a, key, a.lower, a.upper)
end
where_binary_range (a: ARRAY [INTEGER]; key: INTEGER; low, high: INTEGER): INTEGER
-- The index of an element `key' within `a[low..high]' if it exists.
-- Otherwise an integer outside `[low..high]'
note
source: "http://arxiv.org/abs/1211.4470"
require
is_sorted (a, low, high)
local
i, j, mid: INTEGER
do
if low > high then
Result := low - 1
else
from
i := low
j := high
mid := low
Result := low - 1
invariant
low <= i and i <= mid + 1
low <= mid and mid <= j and j <= high
i <= j
has (a, key, i, j) = has (a, key, low, high)
until
i >= j
loop
mid := i + (j - i) // 2
if a [mid] < key then
i := mid + 1
else
j := mid
end
variant
j - i
end
if a [i] = key then
Result := i
end
end
ensure
low <= Result and Result <= high implies a [Result] = key
Result < low or Result > high implies not has (a, key, low, high)
end
feature -- Implementation
is_sorted (a: ARRAY [INTEGER]; low, high: INTEGER): BOOLEAN
-- Is `a[low..high]' sorted in nondecreasing order?
require
a.lower <= low
high <= a.upper
do
Result := across low |..| (high - 1) as i all a [i.item] <= a [i.item + 1] end
end
has (a: ARRAY [INTEGER]; key: INTEGER; low, high: INTEGER): BOOLEAN
-- Is there an element `key' in `a[low..high]'?
require
a.lower <= low
high <= a.upper
do
Result := across low |..| high as i some a [i.item] = key end
end
end

View file

@ -0,0 +1,22 @@
defmodule Binary do
def search(list, value), do: search(List.to_tuple(list), value, 0, length(list)-1)
def search(_tuple, _value, low, high) when high < low, do: :not_found
def search(tuple, value, low, high) do
mid = div(low + high, 2)
midval = elem(tuple, mid)
cond do
value < midval -> search(tuple, value, low, mid-1)
value > midval -> search(tuple, value, mid+1, high)
value == midval -> mid
end
end
end
list = [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]
Enum.each([0,42,45,24324,99999], fn val ->
case Binary.search(list, val) do
:not_found -> IO.puts "#{val} not found in list"
index -> IO.puts "found #{val} at index #{index}"
end
end)

View file

@ -0,0 +1,10 @@
(defun binary-search (value array)
(let ((low 0)
(high (1- (length array))))
(cl-do () ((< high low) nil)
(let ((middle (floor (+ low high) 2)))
(cond ((> (aref array middle) value)
(setf high (1- middle)))
((< (aref array middle) value)
(setf low (1+ middle)))
(t (cl-return middle)))))))

View file

@ -0,0 +1,27 @@
%% Task: Binary Search algorithm
%% Author: Abhay Jain
-module(searching_algorithm).
-export([start/0]).
start() ->
List = [1,2,3],
binary_search(List, 5, 1, length(List)).
binary_search(List, Value, Low, High) ->
if Low > High ->
io:format("Number ~p not found~n", [Value]),
not_found;
true ->
Mid = (Low + High) div 2,
MidNum = lists:nth(Mid, List),
if MidNum > Value ->
binary_search(List, Value, Low, Mid-1);
MidNum < Value ->
binary_search(List, Value, Mid+1, High);
true ->
io:format("Number ~p found at index ~p", [Value, Mid]),
Mid
end
end.

View file

@ -0,0 +1,16 @@
function binary_search(sequence s, object val, integer low, integer high)
integer mid, cmp
if high < low then
return 0 -- not found
else
mid = floor( (low + high) / 2 )
cmp = compare(s[mid], val)
if cmp > 0 then
return binary_search(s, val, low, mid-1)
elsif cmp < 0 then
return binary_search(s, val, mid+1, high)
else
return mid
end if
end if
end function

View file

@ -0,0 +1,17 @@
function binary_search(sequence s, object val)
integer low, high, mid, cmp
low = 1
high = length(s)
while low <= high do
mid = floor( (low + high) / 2 )
cmp = compare(s[mid], val)
if cmp > 0 then
high = mid - 1
elsif cmp < 0 then
low = mid + 1
else
return mid
end if
end while
return 0 -- not found
end function

View file

@ -0,0 +1,12 @@
let rec binarySearch (myArray:array<IComparable>, low:int, high:int, value:IComparable) =
if (high < low) then
null
else
let mid = (low + high) / 2
if (myArray.[mid] > value) then
binarySearch (myArray, low, mid-1, value)
else if (myArray.[mid] < value) then
binarySearch (myArray, mid+1, high, value)
else
myArray.[mid]

View file

@ -0,0 +1,22 @@
#APPTYPE CONSOLE
DIM va[], sign = {1, -1}, toggle
PRINT "Loading ... ";
DIM gtc = GetTickCount()
FOR DIM i = 0 TO 1000000
va[] = sign[toggle] * PI * i
toggle = NOT toggle ' randomize the array
NEXT
PRINT "done in ", GetTickCount() - gtc, " milliseconds"
PRINT "Sorting ... ";
gtc = GetTickCount()
QUICKSORT(va) ' quick sort the array
PRINT "done in ", GetTickCount() - gtc, " milliseconds"
gtc = GetTickCount()
PRINT 1000000 * PI, " found at index ", BSEARCH(va, 1000000 * PI), _ ' binary search through the array
" in ", GetTickCount() - gtc, " milliseconds"
PAUSE

View file

@ -0,0 +1,29 @@
#APPTYPE CONSOLE
DIM va[]
PRINT "Loading ... ";
DIM gtc = GetTickCount()
FOR DIM i = 0 TO 1000000: va[] = i * PI: NEXT
PRINT "done in ", GetTickCount() - gtc, " milliseconds"
gtc = GetTickCount()
PRINT 1000000 * PI, " found at index ", BSearchIter(va, 1000000 * PI), _
" in ", GetTickCount() - gtc, " milliseconds"
PAUSE
FUNCTION BSearchIter(BYVAL array, BYVAL num)
STATIC low = LBOUND(va), high = UBOUND(va)
WHILE low <= high
DIM midp = (high + low) \ 2
IF array[midp] > num THEN
high = midp - 1
ELSEIF array[midp] < num THEN
low = midp + 1
ELSE
RETURN midp
END IF
WEND
RETURN -1
END FUNCTION

View file

@ -0,0 +1,25 @@
#APPTYPE CONSOLE
DIM va[]
PRINT "Loading ... ";
DIM gtc = GetTickCount()
FOR DIM i = 0 TO 1000000: va[] = i * PI: NEXT
PRINT "done in ", GetTickCount() - gtc, " milliseconds"
gtc = GetTickCount()
PRINT 1000000 * PI, " found at index ", BSearchRec(va, 1000000 * PI, LBOUND(va), UBOUND(va)), _
" in ", GetTickCount() - gtc, " milliseconds"
PAUSE
FUNCTION BSearchRec(BYVAL array, BYVAL num, BYVAL low, BYVAL high)
IF high < low THEN RETURN -1
DIM midp = (high + low) \ 2
IF array[midp] > num THEN
RETURN BSearchRec(array, num, low, midp - 1)
ELSEIF array[midp] < num THEN
RETURN BSearchRec(array, num, midp + 1, high)
END IF
RETURN midp
END FUNCTION

View file

@ -0,0 +1,4 @@
USING: binary-search kernel math.order ;
: binary-search ( seq elt -- index/f )
[ [ <=> ] curry search ] keep = [ drop f ] unless ;

View file

@ -0,0 +1,31 @@
defer (compare)
' - is (compare) \ default to numbers
: cstr-compare ( cstr1 cstr2 -- <=> ) \ counted strings
swap count rot count compare ;
: mid ( u l -- mid ) tuck - 2/ -cell and + ;
: bsearch ( item upper lower -- where found? )
rot >r
begin 2dup >
while 2dup mid
dup @ r@ (compare)
dup
while 0<
if nip cell+ ( upper mid+1 )
else rot drop swap ( mid lower )
then
repeat drop nip nip true
else max ( insertion-point ) false
then
r> drop ;
create test 2 , 4 , 6 , 9 , 11 , 99 ,
: probe ( n -- ) test 5 cells bounds bsearch . @ . cr ;
1 probe \ 0 2
2 probe \ -1 2
3 probe \ 0 4
10 probe \ 0 11
11 probe \ -1 11
12 probe \ 0 99

View file

@ -0,0 +1,18 @@
recursive function binarySearch_R (a, value) result (bsresult)
real, intent(in) :: a(:), value
integer :: bsresult, mid
mid = size(a)/2 + 1
if (size(a) == 0) then
bsresult = 0 ! not found
else if (a(mid) > value) then
bsresult= binarySearch_R(a(:mid-1), value)
else if (a(mid) < value) then
bsresult = binarySearch_R(a(mid+1:), value)
if (bsresult /= 0) then
bsresult = mid + bsresult
end if
else
bsresult = mid ! SUCCESS!!
end if
end function binarySearch_R

View file

@ -0,0 +1,23 @@
function binarySearch_I (a, value)
integer :: binarySearch_I
real, intent(in), target :: a(:)
real, intent(in) :: value
real, pointer :: p(:)
integer :: mid, offset
p => a
binarySearch_I = 0
offset = 0
do while (size(p) > 0)
mid = size(p)/2 + 1
if (p(mid) > value) then
p => p(:mid-1)
else if (p(mid) < value) then
offset = offset + mid
p => p(mid+1:)
else
binarySearch_I = offset + mid ! SUCCESS!!
return
end if
end do
end function binarySearch_I

View file

@ -0,0 +1,20 @@
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.
REAL X,A(*) !Where is X in array A(1:N)?
INTEGER N !The count.
INTEGER L,R,P !Fingers.
L = 0 !Establish outer bounds, to search A(L+1:R-1).
R = N + 1 !L = first - 1; R = last + 1.
1 P = (R - L)/2 !Probe point. Beware INTEGER overflow with (L + R)/2.
IF (P.LE.0) GO TO 5 !Aha! Nowhere!! The span is empty.
P = P + L !Convert an offset from L to an array index.
IF (X - A(P)) 3,4,2 !Compare to the probe point.
2 L = P !A(P) < X. Shift the left bound up: X follows A(P).
GO TO 1 !Another chop.
3 R = P !X < A(P). Shift the right bound down: X precedes A(P).
GO TO 1 !Try again.
4 FINDI = P !A(P) = X. So, X is found, here!
RETURN !Done.
Curse it!
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.

View file

@ -0,0 +1,20 @@
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.
REAL X,A(*) !Where is X in array A(1:N)?
INTEGER N !The count.
INTEGER L,R,P !Fingers.
L = 0 !Establish outer bounds, to search A(L+1:R-1).
R = N + 1 !L = first - 1; R = last + 1.
GO TO 1 !Hop to it.
2 L = P !A(P) < X. Shift the left bound up: X follows A(P).
1 P = (R - L)/2 !Probe point. Beware INTEGER overflow with (L + R)/2.
IF (P.LE.0) GO TO 5 !Aha! Nowhere!! The span is empty.
P = P + L !Convert an offset from L to an array index.
IF (X - A(P)) 3,4,2 !Compare to the probe point.
3 R = P !X < A(P). Shift the right bound down: X precedes A(P).
GO TO 1 !Try again.
4 FINDI = P !A(P) = X. So, X is found, here!
RETURN !Done.
Curse it!
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.

View file

@ -0,0 +1,12 @@
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
dim as uinteger lo = lbound(array), hi = ubound(array), md = (lo + hi)\2
if array(lo) = target then return lo
if array(hi) = target then return hi
while lo + 1 < hi
if array(md) = target then return md
if array(md)<target then lo = md else hi = md
md = (lo + hi)\2
wend
return -1
end function

View file

@ -0,0 +1,13 @@
fun main(as: [n]int, value: int): int =
let low = 0
let high = n-1
loop ((low,high)) = while low <= high do
-- invariants: value > as[i] for all i < low
-- value < as[i] for all i > high
let mid = (low+high) / 2
in if as[mid] > value
then (low, mid - 1)
else if as[mid] < value
then (mid + 1, high)
else (mid, mid-1) -- Force termination.
in low

View file

@ -0,0 +1,23 @@
Find := function(v, x)
local low, high, mid;
low := 1;
high := Length(v);
while low <= high do
mid := QuoInt(low + high, 2);
if v[mid] > x then
high := mid - 1;
elif v[mid] < x then
low := mid + 1;
else
return mid;
fi;
od;
return fail;
end;
u := [1..10]*7;
# [ 7, 14, 21, 28, 35, 42, 49, 56, 63, 70 ]
Find(u, 34);
# fail
Find(u, 35);
# 5

View file

@ -0,0 +1,24 @@
10 REM Binary search
20 DIM A(10)
30 N% = 10
40 FOR I% = 0 TO 9: READ A(I%): NEXT I%
50 REM Sorted data
60 DATA -31, 0, 1, 2, 2, 4, 65, 83, 99, 782
70 X = 2: GOSUB 500
80 GOSUB 200
90 X = 5: GOSUB 500
100 GOSUB 200
110 END
190 REM Print result
200 PRINT X;
210 IF INDX% >= 0 THEN PRINT "is at index"; STR$(INDX%);"." ELSE PRINT "is not found."
220 RETURN
480 REM Binary search algorithm
490 REM N% - number of elements; X - searched element; Result: INDX% - index of X
500 L% = 0: H% = N% - 1: FOUND% = 0
510 WHILE (L% <= H%) AND NOT FOUND%
520 M% = L% + (H% - L%) \ 2
530 IF A(M%) < X THEN L% = M% + 1 ELSE IF A(M%) > X THEN H% = M% - 1 ELSE FOUND% = -1
540 WEND
550 IF FOUND% = 0 THEN INDX% = -1 ELSE INDX% = M%
560 RETURN

View file

@ -0,0 +1,12 @@
func binarySearch(a []float64, value float64, low int, high int) int {
if high < low {
return -1
}
mid := (low + high) / 2
if a[mid] > value {
return binarySearch(a, value, low, mid-1)
} else if a[mid] < value {
return binarySearch(a, value, mid+1, high)
}
return mid
}

View file

@ -0,0 +1,15 @@
func binarySearch(a []float64, value float64) int {
low := 0
high := len(a) - 1
for low <= high {
mid := (low + high) / 2
if a[mid] > value {
high = mid - 1
} else if a[mid] < value {
low = mid + 1
} else {
return mid
}
}
return -1
}

View file

@ -0,0 +1,5 @@
import "sort"
//...
sort.SearchInts([]int{0,1,4,5,6,7,8,9}, 6) // evaluates to 4

View file

@ -0,0 +1,13 @@
def binSearchR
//define binSearchR closure.
binSearchR = { a, key, offset=0 ->
def m = n.intdiv(2)
def n = a.size()
a.empty \
? ["The insertion point is": offset] \
: a[m] > key \
? binSearchR(a[0..<m],key, offset) \
: a[m] < target \
? binSearchR(a[(m + 1)..<n],key, offset + m + 1) \
: [index: offset + m]
}

View file

@ -0,0 +1,17 @@
def binSearchI = { aList, target ->
def a = aList
def offset = 0
while (!a.empty) {
def n = a.size()
def m = n.intdiv(2)
if(a[m] > target) {
a = a[0..<m]
} else if (a[m] < target) {
a = a[(m + 1)..<n]
offset += m + 1
} else {
return [index: offset + m]
}
}
return ["insertion point": offset]
}

View file

@ -0,0 +1,17 @@
def a = [] as Set
def random = new Random()
while (a.size() < 20) { a << random.nextInt(30) }
def source = a.sort()
source[0..-2].eachWithIndex { si, i -> assert si < source[i+1] }
println "${source}"
1.upto(5) {
target = random.nextInt(10) + (it - 2) * 10
print "Trial #${it}. Looking for: ${target}"
def answers = [binSearchR, binSearchI].collect { search ->
search(source, target)
}
assert answers[0] == answers[1]
println """
Answer: ${answers[0]}, : ${source[answers[0].values().iterator().next()]}"""
}

View file

@ -0,0 +1,52 @@
import Data.Array (Array, Ix, (!), listArray, bounds)
-- BINARY SEARCH --------------------------------------------------------------
bSearch
:: Integral a
=> (a -> Ordering) -> (a, a) -> Maybe a
bSearch p (low, high)
| high < low = Nothing
| otherwise =
let mid = (low + high) `div` 2
in case p mid of
LT -> bSearch p (low, mid - 1)
GT -> bSearch p (mid + 1, high)
EQ -> Just mid
-- Application to an array:
bSearchArray
:: (Ix i, Integral i, Ord e)
=> Array i e -> e -> Maybe i
bSearchArray a x = bSearch (compare x . (a !)) (bounds a)
-- TEST -----------------------------------------------------------------------
axs
:: (Num i, Ix i)
=> Array i String
axs =
listArray
(0, 11)
[ "alpha"
, "beta"
, "delta"
, "epsilon"
, "eta"
, "gamma"
, "iota"
, "kappa"
, "lambda"
, "mu"
, "theta"
, "zeta"
]
main :: IO ()
main =
let e = "mu"
found = bSearchArray axs e
in putStrLn $
'\'' :
e ++
case found of
Nothing -> "' Not found"
Just x -> "' found at index " ++ show x

View file

@ -0,0 +1,46 @@
import Data.Array (Array, Ix, (!), listArray, bounds)
-- BINARY SEARCH USING A HELPER FUNCTION WITH A SIMPLER TYPE SIGNATURE
findIndexBinary
:: Ord a
=> (a -> Ordering) -> Array Int a -> Either String Int
findIndexBinary p axs =
let go (lo, hi)
| hi < lo = Left "not found"
| otherwise =
let mid = (lo + hi) `div` 2
in case p (axs ! mid) of
LT -> go (lo, pred mid)
GT -> go (succ mid, hi)
EQ -> Right mid
in go (bounds axs)
-- TEST ---------------------------------------------------
haystack :: Array Int String
haystack =
listArray
(0, 11)
[ "alpha"
, "beta"
, "delta"
, "epsilon"
, "eta"
, "gamma"
, "iota"
, "kappa"
, "lambda"
, "mu"
, "theta"
, "zeta"
]
main :: IO ()
main =
let needle = "lambda"
in putStrLn $
'\'' :
needle ++
either
("' " ++)
(("' found at index " ++) . show)
(findIndexBinary (compare needle) haystack)

View file

@ -0,0 +1,50 @@
import Data.Array (Array, Ix, (!), listArray, bounds)
-- BINARY SEARCH USING THE ITERATIVE ALGORITHM
findIndexBinary_
:: Ord a
=> (a -> Ordering) -> Array Int a -> Either String Int
findIndexBinary_ p axs =
let (lo, hi) =
until
(\(lo, hi) -> lo > hi || 0 == hi)
(\(lo, hi) ->
let m = quot (lo + hi) 2
in case p (axs ! m) of
LT -> (lo, pred m)
GT -> (succ m, hi)
EQ -> (m, 0))
(bounds axs) :: (Int, Int)
in if 0 /= hi
then Left "not found"
else Right lo
-- TEST ---------------------------------------------------
haystack :: Array Int String
haystack =
listArray
(0, 11)
[ "alpha"
, "beta"
, "delta"
, "epsilon"
, "eta"
, "gamma"
, "iota"
, "kappa"
, "lambda"
, "mu"
, "theta"
, "zeta"
]
main :: IO ()
main =
let needle = "kappa"
in putStrLn $
'\'' :
needle ++
either
("' " ++)
(("' found at index " ++) . show)
(findIndexBinary_ (compare needle) haystack)

View file

@ -0,0 +1,32 @@
REAL :: n=10, array(n)
array = NINT( RAN(n) )
SORT(Vector=array, Sorted=array)
x = NINT( RAN(n) )
idx = binarySearch( array, x )
WRITE(ClipBoard) x, "has position ", idx, "in ", array
END
FUNCTION binarySearch(A, value)
REAL :: A(1), value
low = 1
high = LEN(A)
DO i = 1, high
IF( low > high) THEN
binarySearch = 0
RETURN
ELSE
mid = INT( (low + high) / 2 )
IF( A(mid) > value) THEN
high = mid - 1
ELSEIF( A(mid) < value ) THEN
low = mid + 1
ELSE
binarySearch = mid
RETURN
ENDIF
ENDIF
ENDDO
END

View file

@ -0,0 +1,2 @@
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

View file

@ -0,0 +1,10 @@
|= [arr=(list @ud) x=@ud]
=/ lo=@ud 0
=/ hi=@ud (dec (lent arr))
|-
?> (lte lo hi)
=/ mid (div (add lo hi) 2)
=/ val (snag mid arr)
?: (lth x val) $(hi (dec mid))
?: (gth x val) $(lo +(mid))
mid

View file

@ -0,0 +1,27 @@
100 PROGRAM "Search.bas"
110 RANDOMIZE
120 NUMERIC ARR(1 TO 20)
130 CALL FILL(ARR)
140 PRINT:INPUT PROMPT "Value: ":N
150 LET IDX=SEARCH(ARR,N)
160 IF IDX THEN
170 PRINT "The value";N;"was found the index";IDX
180 ELSE
190 PRINT "The value";N;"was not found."
200 END IF
210 DEF FILL(REF T)
220 LET T(LBOUND(T))=RND(3):PRINT T(1);
230 FOR I=LBOUND(T)+1 TO UBOUND(T)
240 LET T(I)=T(I-1)+RND(3)+1
250 PRINT T(I);
260 NEXT
270 END DEF
280 DEF SEARCH(REF T,N)
290 LET SEARCH=0:LET BO=LBOUND(T):LET UP=UBOUND(T)
300 DO
310 LET K=INT((BO+UP)/2)
320 IF T(K)<N THEN LET BO=K+1
330 IF T(K)>N THEN LET UP=K-1
340 LOOP WHILE BO<=UP AND T(K)<>N
350 IF BO<=UP THEN LET SEARCH=K
360 END DEF

View file

@ -0,0 +1,11 @@
procedure binsearch(A, target)
if *A = 0 then fail
mid := *A/2 + 1
if target > A[mid] then {
return mid + binsearch(A[(mid+1):0], target)
}
else if target < A[mid] then {
return binsearch(A[1+:(mid-1)], target)
}
return mid
end

View file

@ -0,0 +1,13 @@
procedure main(args)
target := integer(!args) | 3
every put(A := [], 1 to 18 by 2)
outList("Searching", A)
write(target," is ",("at "||binsearch(A, target)) | "not found")
end
procedure outList(prefix, A)
writes(prefix,": ")
every writes(!A," ")
write()
end

View file

@ -0,0 +1 @@
bs=. i. 'Not Found'"_^:(-.@-:) I.

View file

@ -0,0 +1,4 @@
2 3 5 6 8 10 11 15 19 20 bs 11
6
2 3 5 6 8 10 11 15 19 20 bs 12
Not Found

View file

@ -0,0 +1,13 @@
'X Y L H M'=. i.5 NB. Setting mnemonics for boxes
f=. &({::) NB. Fetching the contents of a box
o=. @: NB. Composing verbs (functions)
boxes=. ; , a: $~ 3: NB. Appending 3 (empty) boxes to the inputs
LowHigh=. (0 ; # o (X f)) (L,H)} ] NB. Setting the low and high bounds
midpoint=. < o (<. o (2 %~ L f + H f)) M} ] NB. Updating the midpoint
case=. >: o * o (Y f - M f { X f) NB. Less=0, equal=1, or greater=2
squeeze=. (< o (_1 + M f) H} ])`(< o _: L} ])`(< o (1 + M f) L} ])@.case
return=. (M f) o ((<@:('Not Found'"_) M} ]) ^: (_ ~: L f))
bs=. return o (squeeze o midpoint ^: (L f <: H f) ^:_) o LowHigh o boxes

View file

@ -0,0 +1,11 @@
'X Y L H M'=. i.5 NB. Setting mnemonics for boxes
f=. &({::) NB. Fetching the contents of a box
o=. @: NB. Composing verbs (functions)
boxes=. a: ,~ ; NB. Appending 1 (empty) box to the inputs
midpoint=. < o (<. o (2 %~ L f + H f)) M} ] NB. Updating the midpoint
case=. >: o * o (Y f - M f { X f) NB. Less=0, equal=1, or greater=2
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 [))

Some files were not shown because too many files have changed in this diff Show more