September 2017 Update

This commit is contained in:
Ingy döt Net 2017-09-23 10:01:46 +02:00
parent bba7bfd280
commit ba8067c3b7
14570 changed files with 153136 additions and 63871 deletions

View file

@ -4,8 +4,8 @@ As an analogy, consider the children's game "[[Guess the number/With feedback|gu
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.
'''The Task'''
;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.
@ -16,7 +16,7 @@ All of the following code examples use an "inclusive" upper bound (i.e. <code>hi
* (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
;Traditional algorithm
The algorithms are as follows (from [[wp:Binary search|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''':
@ -53,7 +53,7 @@ The algorithms are as follows (from [[wp:Binary search|Wikipedia]]). The algorit
return not_found // value would be inserted at index "low"
}
; Leftmost insertion point
;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''':
@ -86,7 +86,7 @@ The following algorithms return the leftmost place where the given element can b
return low
}
; Rightmost insertion point
;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''':
@ -122,7 +122,7 @@ The following algorithms return the rightmost place where the given element can
;Extra credit
Make sure it does not have overflow bugs.
The line in the pseudocode above to calculate the mean of two integers:
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.
@ -134,7 +134,12 @@ 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.
'''References:'''<br>
:* C.f: [[Guess the number/With Feedback (Player)]]
;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,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,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

@ -1,36 +0,0 @@
/* http://www.solipsys.co.uk/b_search/spec.htm */
typedef int Object;
int cmpObject(Object* pa, Object *pb)
{
Object a = *pa;
Object b = *pb;
if (a < b) return -1;
if (a == b) return 0;
if (a > b) return 1;
assert(0);
}
int bsearch(Object Array[], int n, Object *KeyPtr,
int (*cmp)(Object *, Object *),
int NotFound)
{
unsigned left = 1, right = n; /* `unsigned' to avoid overflow in `(left + right)/2' */
if ( ! (Array && n > 0 && KeyPtr && cmp))
return NotFound; /* invalid input or empty array */
while (left < right)
{
/* invariant: a[left] <= *KeyPtr <= a[right] or *KeyPtr not in Array */
unsigned m = (left + right) / 2; /*NOTE: *intentionally* truncate for odd sum */
if (cmp(Array + m, KeyPtr) < 0)
left = m + 1; /* a[m] < *KeyPtr <= a[right] or *KeyPtr not in Array */
else
/* assert(right != m) or infinite loop possible */
right = m; /* a[left] <= *KeyPtr <= a[m] or *KeyPtr not in Array */
}
/* assert(left == right) */
return (cmp(Array + right, KeyPtr) == 0) ? right : NotFound;
}

View file

@ -1,38 +0,0 @@
#define DUMMY -1 /* dummy element of array (to adjust indexing from 1..n) */
int main(void)
{
Object a[] = {DUMMY, 0, 1, 1, 2, 5}; /* allowed indices from 1 to n including */
int n = sizeof(a)/sizeof(*a) - 1;
const int NotFound = -1;
/* key not in Array */
Object key = 4;
assert(NotFound == bsearch(a, n, &key, cmpObject, NotFound));
key = DUMMY;
assert(NotFound == bsearch(a, n, &key, cmpObject, NotFound));
key = 7;
assert(NotFound == bsearch(a, n, &key, cmpObject, NotFound));
/* all possible `n' and `k' for `a' array */
int k;
key = 10; /* not in `a` array */
for (n = 0; n <= sizeof(a)/sizeof(*a) - 1; ++n)
for (k = n; k>=1; --k) {
int index = bsearch(a, n, &a[k], cmpObject, NotFound);
assert(index == k || (k==3 && index == 2) || n == 0); /* for equal `1's */
assert(NotFound == bsearch(a, n, &key, cmpObject, NotFound));
}
n = sizeof(a)/sizeof(*a) - 1;
/* NULL array */
assert(NotFound == bsearch(NULL, n, &key, cmpObject, NotFound));
/* NULL &key */
assert(NotFound == bsearch(a, n, NULL, cmpObject, NotFound));
/* NULL cmpObject */
assert(1 == bsearch(a, n, &a[1], cmpObject, NotFound));
assert(NotFound == bsearch(a, n, &a[1], NULL, NotFound));
printf("OK\n");
return 0;
}

View file

@ -1,21 +0,0 @@
#include <stdlib.h> /* for bsearch */
#include <stdio.h>
int intcmp(const void *a, const void *b)
{
/* this is only correct if it doesn't overflow */
return *(const int *)a - *(const int *)b;
}
int main()
{
int nums[5] = {2, 3, 5, 6, 8};
int desired = 6;
int *ptr = bsearch(&desired, nums, 5, sizeof(int), intcmp);
if (ptr == NULL)
printf("not found\n");
else
printf("index = %d\n", ptr - nums);
return 0;
}

View file

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

View file

@ -1,9 +0,0 @@
binarySearch :: Integral a => (a -> Ordering) -> (a, a) -> Maybe a
binarySearch p (low,high)
| high < low = Nothing
| otherwise =
let mid = (low + high) `div` 2 in
case p mid of
LT -> binarySearch p (low, mid-1)
GT -> binarySearch p (mid+1, high)
EQ -> Just mid

View file

@ -1,5 +0,0 @@
import Data.Array
binarySearchArray :: (Ix i, Integral i, Ord e) => Array i e -> e -> Maybe i
binarySearchArray a x = binarySearch p (bounds a) where
p m = x `compare` (a ! m)

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

@ -1,27 +1,29 @@
...
//check will be the number we are looking for
//nums will be the array we are searching through
public static int binarySearch(int[] nums, int check){
public class BinarySearchIterative {
public static int binarySearch(int[] nums, int check) {
int hi = nums.length - 1;
int lo = 0;
while(hi >= lo){
int guess = lo + ((hi - lo) / 2);
if(nums[guess] > check){
hi = guess - 1;
}else if(nums[guess] < check){
lo = guess + 1;
}else{
return guess;
}
while (hi >= lo) {
int guess = lo + ((hi - lo) / 2);
if (nums[guess] > check) {
hi = guess - 1;
} else if (nums[guess] < check) {
lo = guess + 1;
} else {
return guess;
}
}
return -1;
}
}
public static void main(String[] args){
int[] searchMe;
int someNumber;
...
int index = binarySearch(searchMe, someNumber);
System.out.println(someNumber + ((index == -1) ? " is not in the array" : (" is at index " + index)));
...
public static void main(String[] args) {
int[] haystack = {1, 5, 6, 7, 8, 11};
int needle = 5;
int index = binarySearch(haystack, needle);
if (index == -1) {
System.out.println(needle + " is not in the array");
} else {
System.out.println(needle + " is at index " + index);
}
}
}

View file

@ -1,21 +1,28 @@
public static void main(String[] args){
int[] searchMe;
int someNumber;
...
int index = binarySearch(searchMe, someNumber, 0, searchMe.length);
System.out.println(someNumber + ((index == -1) ? " is not in the array" : (" is at index " + index)));
...
}
public class BinarySearchRecursive {
public static int binarySearch(int[] nums, int check, int lo, int hi){
if(hi < lo){
return -1; //impossible index for "not found"
public static int binarySearch(int[] haystack, int needle, int lo, int hi) {
if (hi < lo) {
return -1;
}
int guess = (hi + lo) / 2;
if(nums[guess] > check){
return binarySearch(nums, check, lo, guess - 1);
}else if(nums[guess]<check){
return binarySearch(nums, check, guess + 1, hi);
if (haystack[guess] > needle) {
return binarySearch(haystack, needle, lo, guess - 1);
} else if (haystack[guess] < needle) {
return binarySearch(haystack, needle, guess + 1, hi);
}
return guess;
}
public static void main(String[] args) {
int[] haystack = {1, 5, 6, 7, 8, 11};
int needle = 5;
int index = binarySearch(haystack, needle, 0, haystack.length);
if (index == -1) {
System.out.println(needle + " is not in the array");
} else {
System.out.println(needle + " is at index " + index);
}
}
}

View file

@ -1,45 +1,38 @@
// iterative search:
fun <T : Comparable<T>> Array<T>.binarySearch(target: T): Int {
fun <T : Comparable<T>> Array<T>.iterativeBinarySearch(target: T): Int {
var hi = size - 1
var lo = 0
while (hi >= lo) {
val guess = lo + (hi - lo) / 2
if (this[guess] > target)
hi = guess - 1
else if (this[guess] < target)
lo = guess + 1
else
return guess
if (this[guess] > target) hi = guess - 1
else if (this[guess] < target) lo = guess + 1
else return guess
}
return -1
}
// recursive search:
fun <T : Comparable<T>> Array<T>.binarySearch(target: T, lo: Int, hi: Int): Int {
if (hi < lo)
return -1
fun <T : Comparable<T>> Array<T>.recursiveBinarySearch(target: T, lo: Int, hi: Int): Int {
if (hi < lo) return -1
val guess = (hi + lo) / 2
return if (this[guess] > target)
binarySearch(target, lo, guess - 1)
else if (this[guess] < target)
binarySearch(target, guess + 1, hi)
else
guess
return if (this[guess] > target) recursiveBinarySearch(target, lo, guess - 1)
else if (this[guess] < target) recursiveBinarySearch(target, guess + 1, hi)
else guess
}
fun main(args: Array<String>) {
val a = intArrayOf(1, 3, 4, 5, 6, 7, 8, 9, 10)
var t = 6 // target
var r = a.binarySearch(t)
println(if (r < 0) "$t not found" else "$t found at index $r")
t = 250
r = a.binarySearch(t)
println(if (r < 0) "$t not found" else "$t found at index $r")
val a = arrayOf(1, 3, 4, 5, 6, 7, 8, 9, 10)
var target = 6
var r = a.iterativeBinarySearch(target)
println(if (r < 0) "$target not found" else "$target found at index $r")
target = 250
r = a.iterativeBinarySearch(target)
println(if (r < 0) "$target not found" else "$target found at index $r")
t = 6
r = a.binarySearch(t, 0, a.size)
println(if (r < 0) "$t not found" else "$t found at index $r")
t = 250
r = a.binarySearch(t, 0, a.size)
println(if (r < 0) "$t not found" else "$t found at index $r")
target = 6
r = a.recursiveBinarySearch(target, 0, a.size)
println(if (r < 0) "$target not found" else "$target found at index $r")
target = 250
r = a.recursiveBinarySearch(target, 0, a.size)
println(if (r < 0) "$target not found" else "$target found at index $r")
}

View file

@ -0,0 +1,28 @@
{def BS
{def BS.r {lambda {:a :v :i0 :i1}
{let { {:a :a} {:v :v} {:i0 :i0} {:i1 :i1}
{:m {floor {* {+ :i0 :i1} 0.5}}} }
{if {< :i1 :i0}
then :v is not found
else {if {> {array.item :a :m} :v}
then {BS.r :a :v :i0 {- :m 1} }
else {if {< {array.item :a :m} :v}
then {BS.r :a :v {+ :m 1} :i1 }
else :v is at array[:m] }}}}} }
{lambda {:a :v}
{BS.r :a :v 0 {- {array.length :a} 1}} }}
-> BS
{def A {array 12 14 16 18 20 22 25 27 30}}
-> A = [12,14,16,18,20,22,25,27,30]
{BS {A} -1} -> -1 is not found
{BS {A} 24} -> 24 is not found
{BS {A} 25} -> 25 is at array[6]
{BS {A} 123} -> 123 is not found
{def B {array {serie 1 100000 2}}}
-> B = [1,3,5,... 99997,99999]
{BS {B} 100} -> 100 is not found
{BS {B} 12345} -> 12345 is at array[6172]

View file

@ -0,0 +1,52 @@
data = .array~of(1, 3, 5, 7, 9, 11)
-- search keys with a number of edge cases
searchkeys = .array~of(0, 1, 4, 7, 11, 12)
say "recursive binary search"
loop key over searchkeys
pos = recursiveBinarySearch(data, key)
if pos == 0 then say "Key" key "not found"
else say "Key" key "found at postion" pos
end
say
say "iterative binary search"
loop key over searchkeys
pos = iterativeBinarySearch(data, key)
if pos == 0 then say "Key" key "not found"
else say "Key" key "found at postion" pos
end
::routine recursiveBinarySearch
-- NB: Rexx arrays are 1-based
use strict arg data, value, low = 1, high = (data~items)
-- make sure we don't go beyond the bounds
high = min(high, data~items)
-- zero indicates not found
if high < low then return 0
mid = (low + high) % 2
if data[mid] > value then
return recursiveBinarySearch(data, value, low, mid - 1)
else if data[mid] < value then
return recursiveBinarySearch(data, value, mid + 1, high)
-- got it!
return mid
::routine iterativeBinarySearch
-- NB: Rexx arrays are 1-based
use strict arg data, value, low = 1, high = (data~items)
-- make sure we don't go beyond the bounds
high = min(high, data~items)
-- zero indicates not found
if high < low then return 0
loop while low <= high
mid = (low + high) % 2
if data[mid] > value then
high = mid - 1
else if data[mid] < value then
low = mid + 1
else
return mid
end
return 0

View file

@ -1,16 +1,20 @@
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)
global function binary_search(object needle, sequence haystack)
integer lo = 1,
hi = length(haystack),
mid = lo,
c = 0
while lo<=hi do
mid = floor((lo+hi)/2)
c = compare(needle, haystack[mid])
if c<0 then
hi = mid-1
elsif c>0 then
lo = mid+1
else
return mid
return mid -- found!
end if
end if
end while
mid += c>0
return -mid -- where it would go, if inserted now
end function

View file

@ -1,17 +1,7 @@
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
?binary_search(0,{1,3,5}) -- -1
?binary_search(1,{1,3,5}) -- 1
?binary_search(2,{1,3,5}) -- -2
?binary_search(3,{1,3,5}) -- 2
?binary_search(4,{1,3,5}) -- -3
?binary_search(5,{1,3,5}) -- 3
?binary_search(6,{1,3,5}) -- -4

View file

@ -0,0 +1,66 @@
function BinarySearch-Iterative ([int[]]$Array, [int]$Value)
{
[int]$low = 0
[int]$high = $Array.Count - 1
while ($low -le $high)
{
[int]$mid = ($low + $high) / 2
if ($Array[$mid] -gt $Value)
{
$high = $mid - 1
}
elseif ($Array[$mid] -lt $Value)
{
$low = $mid + 1
}
else
{
return $mid
}
}
return -1
}
function BinarySearch-Recursive ([int[]]$Array, [int]$Value, [int]$Low = 0, [int]$High = $Array.Count)
{
if ($High -lt $Low)
{
return -1
}
[int]$mid = ($Low + $High) / 2
if ($Array[$mid] -gt $Value)
{
return BinarySearch $Array $Value $Low ($mid - 1)
}
elseif ($Array[$mid] -lt $Value)
{
return BinarySearch $Array $Value ($mid + 1) $High
}
else
{
return $mid
}
}
function Show-SearchResult ([int[]]$Array, [int]$Search, [ValidateSet("Iterative", "Recursive")][string]$Function)
{
switch ($Function)
{
"Iterative" {$index = BinarySearch-Iterative -Array $Array -Value $Search}
"Recursive" {$index = BinarySearch-Recursive -Array $Array -Value $Search}
}
if ($index -ge 0)
{
Write-Host ("Using BinarySearch-{0}: {1} is at index {2}" -f $Function, $numbers[$index], $index)
}
else
{
Write-Host ("Using BinarySearch-{0}: {1} not found" -f $Function, $Search) -ForegroundColor Red
}
}

View file

@ -0,0 +1,4 @@
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 86 -Function Recursive
Show-SearchResult -Array 10, 28, 41, 46, 58, 74, 76, 86, 89, 98 -Search 11 -Function Recursive

View file

@ -1,10 +1,12 @@
def binarySearch[A <% Ordered[A]](xs: Seq[A], x: A): Option[Int] = {
var (low, high) = (0, xs.size - 1)
while (low <= high)
(low + high) / 2 match {
case mid if xs(mid) > x => high = mid - 1
case mid if xs(mid) < x => low = mid + 1
case mid => return Some(mid)
}
None
}
def binarySearch[T](xs: Seq[T], x: T)(implicit ordering: Ordering[T]): Option[Int] = {
var low: Int = 0
var high: Int = xs.size - 1
while (low <= high)
low + high >>> 1 match {
case guess if ordering.gt(xs(guess), x) => high = guess - 1 //too high
case guess if ordering.lt(xs(guess), x) => low = guess + 1 // too low
case guess => return Some(guess) //found it
}
None //not found
}

View file

@ -1,14 +1,14 @@
func binary_search(a, i) {
var l = 0;
var h = a.end;
var l = 0
var h = a.end
while (l <= h) {
var mid = (h+l / 2 -> int);
a[mid] > i && (h = mid-1; next);
a[mid] < i && (l = mid+1; next);
return mid;
var mid = (h+l / 2 -> int)
a[mid] > i && (h = mid-1; next)
a[mid] < i && (l = mid+1; next)
return mid
}
return -1;
return -1
}

View file

@ -1,13 +1,16 @@
func binary_search(arr, value, low=0, high=arr.end) {
high < low && return -1;
var middle = (high+low / 2 -> int);
high < low && return -1
var middle = ((high+low) // 2)
if (value < arr[middle]) {
return binary_search(arr, value, low, middle-1);
given (arr[middle]) { |item|
case (value < item) {
binary_search(arr, value, low, middle-1)
}
case (value > item) {
binary_search(arr, value, middle+1, high)
}
case (value == item) {
middle
}
}
elsif (value > arr[middle]) {
return binary_search(arr, value, middle+1, high);
}
return middle;
}

View file

@ -0,0 +1,9 @@
fcn bsearch(list,value){ // list is sorted
fcn(list,value, low,high){
if (high < low) return(Void); // not found
mid:=(low + high) / 2;
if (list[mid] > value) return(self.fcn(list,value, low, mid-1));
if (list[mid] < value) return(self.fcn(list,value, mid+1, high));
return(mid); // found
}(list,value,0,list.len()-1);
}

View file

@ -0,0 +1,6 @@
list:=T(1,3,5,7,9,11); println("Sorted values: ",list);
foreach i in ([0..12]){
n:=bsearch(list,i);
if (Void==n) println("Not found: ",i);
else println("found ",i," at index ",n);
}