langs a-z

This commit is contained in:
Ingy döt Net 2013-04-10 22:43:41 -07:00
parent db842d013d
commit d066446780
11389 changed files with 98361 additions and 1020 deletions

View file

@ -0,0 +1,10 @@
1 2 3 4 5
3 bsearch . ( => 2 )
5 bsearch . ( => 0 )
'sam 'tom 'kenny ( must be sorted before calling bsearch )
sort
.s ( => kenny sam tom )
'sam bsearch . ( => 1 )
'tom bsearch . ( => 0 )
'kenny bsearch . ( => 2 )
'tony bsearch . ( => -1)

View file

@ -0,0 +1,13 @@
let rec binary_search a value low high =
if high = low then
if a.(low) = value then
low
else
raise Not_found
else let mid = (low + high) / 2 in
if a.(mid) > value then
binary_search a value low (mid - 1)
else if a.(mid) < value then
binary_search a value (mid + 1) high
else
mid

View file

@ -0,0 +1,32 @@
use Structure;
bundle Default {
class BinarySearch {
function : Main(args : String[]) ~ Nil {
values := [-1, 3, 8, 13, 22];
DoBinarySearch(values, 13)->PrintLine();
DoBinarySearch(values, 7)->PrintLine();
}
function : native : DoBinarySearch(values : Int[], value : Int) ~ Int {
low := 0;
high := values->Size() - 1;
while(low <= high) {
mid := (low + high) / 2;
if(values[mid] > value) {
high := mid - 1;
}
else if(values[mid] < value) {
low := mid + 1;
}
else {
return mid;
};
};
return -1;
}
}
}

View file

@ -0,0 +1,51 @@
#import <Foundation/Foundation.h>
@interface NSArray (BinarySearch)
// Requires all elements of this array to implement a -compare: method which
// returns a NSComparisonResult for comparison.
// Returns NSNotFound when not found
- (NSInteger) binarySearch:(id)key;
@end
@implementation NSArray (BinarySearch)
- (NSInteger) binarySearch:(id)key {
NSInteger lo = 0;
NSInteger hi = [self count] - 1;
while (lo <= hi) {
NSInteger mid = lo + (hi - lo) / 2;
id midVal = [self objectAtIndex:mid];
switch ([midVal compare:key]) {
case NSOrderedAscending:
lo = mid + 1;
break;
case NSOrderedDescending:
hi = mid - 1;
break;
case NSOrderedSame:
return mid;
}
}
return NSNotFound;
}
@end
int main()
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *a = [NSArray arrayWithObjects:
[NSNumber numberWithInt: 1],
[NSNumber numberWithInt: 3],
[NSNumber numberWithInt: 4],
[NSNumber numberWithInt: 5],
[NSNumber numberWithInt: 6],
[NSNumber numberWithInt: 7],
[NSNumber numberWithInt: 8],
[NSNumber numberWithInt: 9],
[NSNumber numberWithInt: 10],
nil];
NSLog(@"6 is at position %d", [a binarySearch:[NSNumber numberWithInt: 6]]); // prints 4
[pool drain];
return 0;
}

View file

@ -0,0 +1,49 @@
#import <Foundation/Foundation.h>
@interface NSArray (BinarySearchRecursive)
// Requires all elements of this array to implement a -compare: method which
// returns a NSComparisonResult for comparison.
// Returns NSNotFound when not found
- (NSInteger) binarySearch:(id)key inRange:(NSRange)range;
@end
@implementation NSArray (BinarySearchRecursive)
- (NSInteger) binarySearch:(id)key inRange:(NSRange)range {
if (range.length == 0)
return NSNotFound;
NSInteger mid = range.location + range.length / 2;
id midVal = [self objectAtIndex:mid];
switch ([midVal compare:key]) {
case NSOrderedAscending:
return [self binarySearch:key
inRange:NSMakeRange(mid + 1, NSMaxRange(range) - (mid + 1))];
case NSOrderedDescending:
return [self binarySearch:key
inRange:NSMakeRange(range.location, mid - range.location)];
default:
return mid;
}
}
@end
int main()
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *a = [NSArray arrayWithObjects:
[NSNumber numberWithInt: 1],
[NSNumber numberWithInt: 3],
[NSNumber numberWithInt: 4],
[NSNumber numberWithInt: 5],
[NSNumber numberWithInt: 6],
[NSNumber numberWithInt: 7],
[NSNumber numberWithInt: 8],
[NSNumber numberWithInt: 9],
[NSNumber numberWithInt: 10],
nil];
NSLog(@"6 is at position %d", [a binarySearch:[NSNumber numberWithInt: 6]
inRange:NSMakeRange(0, [a count])]); // prints 4
[pool drain];
return 0;
}

View file

@ -0,0 +1,25 @@
#import <Foundation/Foundation.h>
int main()
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *a = [NSArray arrayWithObjects:
[NSNumber numberWithInt: 1],
[NSNumber numberWithInt: 3],
[NSNumber numberWithInt: 4],
[NSNumber numberWithInt: 5],
[NSNumber numberWithInt: 6],
[NSNumber numberWithInt: 7],
[NSNumber numberWithInt: 8],
[NSNumber numberWithInt: 9],
[NSNumber numberWithInt: 10],
nil];
NSLog(@"6 is at position %lu", [a indexOfObject:[NSNumber numberWithInt: 6]
inSortedRange:NSMakeRange(0, [a count])
options:0
usingComparator:^(id x, id y){ return [x compare: y]; }]); // prints 4
[pool drain];
return 0;
}

View file

@ -0,0 +1,30 @@
#import <Foundation/Foundation.h>
CFComparisonResult myComparator(const void *x, const void *y, void *context) {
return [(id)x compare:(id)y];
}
int main()
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *a = [NSArray arrayWithObjects:
[NSNumber numberWithInt: 1],
[NSNumber numberWithInt: 3],
[NSNumber numberWithInt: 4],
[NSNumber numberWithInt: 5],
[NSNumber numberWithInt: 6],
[NSNumber numberWithInt: 7],
[NSNumber numberWithInt: 8],
[NSNumber numberWithInt: 9],
[NSNumber numberWithInt: 10],
nil];
NSLog(@"6 is at position %d", CFArrayBSearchValues((CFArrayRef)a,
CFRangeMake(0, [a count]),
[NSNumber numberWithInt: 6],
myComparator,
NULL)); // prints 4
[pool drain];
return 0;
}

View file

@ -0,0 +1,14 @@
function i = binsearch_r(array, val, low, high)
if ( high < low )
i = 0;
else
mid = floor((low + high) / 2);
if ( array(mid) > val )
i = binsearch_r(array, val, low, mid-1);
elseif ( array(mid) < val )
i = binsearch_r(array, val, mid+1, high);
else
i = mid;
endif
endif
endfunction

View file

@ -0,0 +1,16 @@
function i = binsearch(array, value)
low = 1;
high = numel(array);
i = 0;
while ( low <= high )
mid = floor((low + high)/2);
if (array(mid) > value)
high = mid - 1;
elseif (array(mid) < value)
low = mid + 1;
else
i = mid;
return;
endif
endwhile
endfunction

View file

@ -0,0 +1,4 @@
r = sort(discrete_rnd(10, [1:10], ones(10,1)/10));
disp(r);
binsearch_r(r, 5, 1, numel(r))
binsearch(r, 5)

View file

@ -0,0 +1,21 @@
declare
fun {BinarySearch Arr Val}
fun {Search Low High}
if Low > High then nil
else
Mid = (Low+High) div 2
in
if Val < Arr.Mid then {Search Low Mid-1}
elseif Val > Arr.Mid then {Search Mid+1 High}
else [Mid]
end
end
end
in
{Search {Array.low Arr} {Array.high Arr}}
end
A = {Tuple.toArray unit(2 3 5 6 8)}
in
{System.printInfo "searching 4: "} {Show {BinarySearch A 4}}
{System.printInfo "searching 8: "} {Show {BinarySearch A 8}}

View file

@ -0,0 +1,19 @@
declare
fun {BinarySearch Arr Val}
Low = {NewCell {Array.low Arr}}
High = {NewCell {Array.high Arr}}
in
for while:@Low =< @High return:Return default:nil do
Mid = (@Low + @High) div 2
in
if Val < Arr.Mid then High := Mid-1
elseif Val > Arr.Mid then Low := Mid+1
else {Return [Mid]}
end
end
end
A = {Tuple.toArray unit(2 3 5 6 8)}
in
{System.printInfo "searching 4: "} {Show {BinarySearch A 4}}
{System.printInfo "searching 8: "} {Show {BinarySearch A 8}}

View file

@ -0,0 +1 @@
setsearch(s, n)

View file

@ -0,0 +1,16 @@
/* A binary search of list A for element M */
search: procedure (A, M) returns (fixed binary);
declare (A(*), M) fixed binary;
declare (l, r, mid) fixed binary;
l = lbound(a,1)-1; r = hbound(A,1)+1;
do while (l+1 < r);
mid = (l+r)/2;
if A(mid) = M then return (mid);
if A(mid) < M then
L = mid;
else
R = mid;
end;
return (lbound(A,1)-1);
end search;

View file

@ -0,0 +1,25 @@
function binary_search(element: real; list: array of real): integer;
var
l, m, h: integer;
begin
l := 0;
h := High(list) - 1;
binary_search := -1;
while l <= h do
begin
m := (l + h) div 2;
if list[m] > element then
begin
h := m - 1;
end
else if list[m] < element then
begin
l := m + 1;
end
else
begin
binary_search := m;
break;
end;
end;
end;

View file

@ -0,0 +1,4 @@
var
list: array[0 .. 9] of real;
// ...
indexof := binary_search(123, list);

View file

@ -0,0 +1,3 @@
sub search (@a, Num $x --> Int) {
binary_search { $x <=> @a[$^i] }, 0, @a.end
}

View file

@ -0,0 +1,11 @@
sub binary_search (&p, Int $lo is copy, Int $hi is copy --> Int) {
until $lo > $hi {
my Int $mid = ($lo + $hi) div 2;
given p $mid {
when -1 { $hi = $mid - 1; }
when 1 { $lo = $mid + 1; }
default { return $mid; }
}
}
fail;
}

View file

@ -0,0 +1,9 @@
sub binary_search (&p, Int $lo, Int $hi --> Int) {
$lo <= $hi or fail;
my Int $mid = ($lo + $hi) div 2;
given p $mid {
when -1 { binary_search &p, $lo, $mid - 1 }
when 1 { binary_search &p, $mid + 1, $hi }
default { $mid }
}
}

View file

@ -0,0 +1,21 @@
define BinarySearch(A, value);
lvars low = 1, high = length(A), mid;
while low <= high do
(low + high) div 2 -> mid;
if A(mid) > value then
mid - 1 -> high;
elseif A(mid) < value then
mid + 1 -> low;
else
return(mid);
endif;
endwhile;
return("not_found");
enddefine;
/* Tests */
lvars A = {2 3 5 6 8};
BinarySearch(A, 4) =>
BinarySearch(A, 5) =>
BinarySearch(A, 8) =>

View file

@ -0,0 +1,16 @@
define BinarySearch(A, value);
define do_it(low, high);
if high < low then
return("not_found");
endif;
(low + high) div 2 -> mid;
if A(mid) > value then
do_it(low, mid-1);
elseif A(mid) < value then
do_it(mid+1, high);
else
mid;
endif;
enddefine;
do_it(1, length(A));
enddefine;

View file

@ -0,0 +1,87 @@
#Recursive = 0 ;recursive binary search method
#Iterative = 1 ;iterative binary search method
#NotFound = -1 ;search result if item not found
;Recursive
Procedure R_BinarySearch(Array a(1), value, low, high)
Protected mid
If high < low
ProcedureReturn #NotFound
EndIf
mid = (low + high) / 2
If a(mid) > value
ProcedureReturn R_BinarySearch(a(), value, low, mid - 1)
ElseIf a(mid) < value
ProcedureReturn R_BinarySearch(a(), value, mid + 1, high)
Else
ProcedureReturn mid
EndIf
EndProcedure
;Iterative
Procedure I_BinarySearch(Array a(1), value, low, high)
Protected mid
While low <= high
mid = (low + high) / 2
If a(mid) > value
high = mid - 1
ElseIf a(mid) < value
low = mid + 1
Else
ProcedureReturn mid
EndIf
Wend
ProcedureReturn #NotFound
EndProcedure
Procedure search (Array a(1), value, method)
Protected idx
Select method
Case #Iterative
idx = I_BinarySearch(a(), value, 0, ArraySize(a()))
Default
idx = R_BinarySearch(a(), value, 0, ArraySize(a()))
EndSelect
Print(" Value " + Str(Value))
If idx < 0
PrintN(" not found")
Else
PrintN(" found at index " + Str(idx))
EndIf
EndProcedure
#NumElements = 9 ;zero based count
Dim test(#NumElements)
DataSection
Data.i 2, 3, 5, 6, 8, 10, 11, 15, 19, 20
EndDataSection
;fill the test array
For i = 0 To #NumElements
Read test(i)
Next
If OpenConsole()
PrintN("Recursive search:")
search(test(), 4, #Recursive)
search(test(), 8, #Recursive)
search(test(), 20, #Recursive)
PrintN("")
PrintN("Iterative search:")
search(test(), 4, #Iterative)
search(test(), 8, #Iterative)
search(test(), 20, #Iterative)
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf

View file

@ -0,0 +1,18 @@
dim theArray(100)
global theArray
for i = 1 to 100
theArray(i) = i
next i
print binarySearch(80,30,90)
FUNCTION binarySearch(val, lo, hi)
IF hi < lo THEN
binarySearch = 0
ELSE
middle = (hi + lo) / 2
if val < theArray(middle) then binarySearch = binarySearch(val, lo, middle-1)
if val > theArray(middle) then binarySearch = binarySearch(val, middle+1, hi)
if val = theArray(middle) then binarySearch = middle
END IF
END FUNCTION

View file

@ -0,0 +1,97 @@
package Binary_Searches is
subtype Item_Type is Integer; -- From specs.
subtype Index_Type is Integer range 1 .. 100;
type Array_Type is array (Index_Type range <>) of Item_Type;
procedure Search (Source : in Array_Type;
Item : in Item_Type;
Found : out Boolean;
Position : out Index_Type);
--# derives Found,
--# Position from
--# Source,
--# Item;
--# post Found -> Source (Position) = Item;
-- If Found is False then Position is undefined.
end Binary_Searches;
package body Binary_Searches is
procedure Search (Source : in Array_Type;
Item : in Item_Type;
Found : out Boolean;
Position : out Index_Type)
is
Lower : Index_Type; -- Lower bound of Subrange.
Upper : Index_Type; -- Upper bound of Subrange.
Terminated : Boolean;
begin
Found := False;
-- Default status updated on success.
Lower := Source'First;
Upper := Source'Last;
Position := (Lower + Upper) / 2;
Terminated := False;
while not Terminated loop
--# assert Lower >= Source'First
--# and Upper <= Source'Last
--# and Position in Lower .. Upper
--# and not Found;
if Item < Source (Position) then
if Position = Lower then
-- No lower subrange.
Terminated := True;
else
--# check Position > Lower;
-- For the two following proofs.
--# check Position - 1 >= Lower;
--# check Lower + Position - 1 >= Lower * 2;
--# check (Lower + Position - 1) / 2 >= Lower;
-- For "Position >= Lower" in loop assertion.
--# check Lower < Position;
--# check Lower + Position - 1 <= (Position - 1) * 2;
--# check (Lower + Position - 1) / 2 <= (Position - 1);
-- For "Position <= Upper" in loop assertion.
-- Switch to lower half subrange.
Upper := Position - 1;
Position := (Lower + Upper) / 2;
end if;
elsif Item > Source (Position) then
if Position = Upper then
-- No upper subrange.
Terminated := True;
else
--# check Position < Upper;
-- For the two following proofs.
--# check Upper >= Position + 1;
--# check Position + 1 + Upper >= (Position + 1) * 2;
--# check (Position + 1 + Upper) / 2 >= (Position + 1);
-- For "Position >= Lower" in loop assertion.
--# check Position + 1 <= Upper;
--# check Position + 1 + Upper <= Upper * 2;
--# check (Position + 1 + Upper) / 2 <= Upper;
-- For "Position <= Upper" in loop assertion.
-- Switch to upper half subrange.
Lower := Position + 1;
Position := (Lower + Upper) / 2;
end if;
else
Found := True;
Terminated := True;
end if;
end loop;
end Search;
end Binary_Searches;

View file

@ -0,0 +1,90 @@
package Binary_Searches is
subtype Item_Type is Integer; -- From specs.
subtype Index_Type is Integer range 1 .. 100;
type Array_Type is array (Index_Type range <>) of Item_Type;
-- Ordered_Between is a 'proof function'. It does not have a code
-- body, but its meaning is defined by a proof rule:
--
-- Ordered_Between (Source, Low_Bound, High_Bound)
-- <->
-- for all I in Index_Type range Low_Bound .. High_Bound - 1 =>
-- (Source(I) < Source(I + 1)) ;
--
--# function Ordered_Between (Source : Array_Type;
--# Range_From, Range_To : Index_Type)
--# return Boolean;
procedure Search (Source : in Array_Type;
Item : in Item_Type;
Found : out Boolean;
Position : out Index_Type);
--# derives Found,
--# Position from
--# Source,
--# Item;
--# pre Ordered_Between (Source, Source'First, Source'Last);
--# post (Found -> (Source (Position) = Item))
--# and (not Found ->
--# (for all I in Index_Type range Source'Range
--# => (Source(I) /= Item)));
end Binary_Searches;
package body Binary_Searches is
procedure Search (Source : in Array_Type;
Item : in Item_Type;
Found : out Boolean;
Position : out Index_Type)
is
Lower : Index_Type; -- Lower bound of Subrange.
Upper : Index_Type; -- Upper bound of Subrange.
Terminated : Boolean;
begin
Found := False;
-- Default status updated on success.
Lower := Source'First;
Upper := Source'Last;
Position := (Lower + Upper) / 2;
Terminated := False;
while not Terminated loop
--# assert not Terminated
--# and not Found
--# and Lower >= Source'First
--# and Upper <= Source'Last
--# and Position in Lower .. Upper
--# and (Lower = Source'First or
--# (Lower > Source'First and Source(Lower - 1) < Item))
--# and (Upper = Source'Last or
--# (Upper < Source'Last and Source(Upper + 1) > Item));
if Item < Source (Position) then
if Position = Lower then
-- No lower subrange.
Terminated := True;
else
-- Switch to lower half subrange.
Upper := Position - 1;
Position := (Lower + Upper) / 2;
end if;
elsif Item > Source (Position) then
if Position = Upper then
-- No upper subrange.
Terminated := True;
else
-- Switch to upper half subrange.
Lower := Position + 1;
Position := (Lower + Upper) / 2;
end if;
else
Found := True;
Terminated := True;
end if;
end loop;
end Search;
end Binary_Searches;

View file

@ -0,0 +1,84 @@
with Binary_Searches;
with SPARK_IO;
--# inherit Binary_Searches,
--# SPARK_IO;
--# main_program;
procedure Test_Binary_Search
--# global in out SPARK_IO.Outputs;
--# derives SPARK_IO.Outputs from *;
is
subtype Index_Type5 is Binary_Searches.Index_Type range 1 .. 5;
subtype Index_Type7 is Binary_Searches.Index_Type range 1 .. 7;
subtype Index_Type9 is Binary_Searches.Index_Type range 91 .. 99;
-- Needed to define a constrained Array_Type.
subtype Array_Type5 is Binary_Searches.Array_Type (Index_Type5);
subtype Array_Type7 is Binary_Searches.Array_Type (Index_Type7);
subtype Array_Type9 is Binary_Searches.Array_Type (Index_Type9);
-- Needed to pass an array literal to Run_Search.
-- SPARK does not allow an unconstrained type mark for that purpose.
procedure Run_Search (Source : in Binary_Searches.Array_Type;
Item : in Binary_Searches.Item_Type)
--# global in out SPARK_IO.Outputs;
--# derives SPARK_IO.Outputs from *,
--# Item,
--# Source;
is
Found : Boolean;
Position : Binary_Searches.Index_Type;
begin
SPARK_IO.Put_String (File => SPARK_IO.Standard_Output,
Item => "Searching for ",
Stop => 0);
SPARK_IO.Put_Integer (File => SPARK_IO.Standard_Output,
Item => Item,
Width => 3,
Base => 10);
SPARK_IO.Put_String (File => SPARK_IO.Standard_Output,
Item => " in (",
Stop => 0);
for Source_Index in Binary_Searches.Index_Type range Source'Range loop
SPARK_IO.Put_Integer (File => SPARK_IO.Standard_Output,
Item => Source (Source_Index),
Width => 3,
Base => 10);
end loop;
SPARK_IO.Put_String (File => SPARK_IO.Standard_Output,
Item => "): ",
Stop => 0);
Binary_Searches.Search (Source => Source, -- in
Item => Item, -- in
Found => Found, -- out
Position => Position); -- out
if Found then
SPARK_IO.Put_String (File => SPARK_IO.Standard_Output,
Item => "found as #",
Stop => 0);
SPARK_IO.Put_Integer (File => SPARK_IO.Standard_Output,
Item => Position,
Width => 0, -- to stick to the sibling '#' sign.
Base => 10);
SPARK_IO.Put_Line (File => SPARK_IO.Standard_Output,
Item => ".",
Stop => 0);
else
SPARK_IO.Put_Line (File => SPARK_IO.Standard_Output,
Item => "not found.",
Stop => 0);
end if;
end Run_Search;
begin
SPARK_IO.New_Line (File => SPARK_IO.Standard_Output, Spacing => 1);
Run_Search (Source => Array_Type5'(0, 1, 2, 3, 4), Item => 3);
Run_Search (Source => Array_Type5'(2, 4, 6, 8, 10), Item => 3);
Run_Search (Source => Array_Type7'(1, 2, 3, 4, 5, 6, 7), Item => 0);
Run_Search (Source => Array_Type7'(1, 2, 3, 4, 5, 6, 7), Item => 7);
Run_Search (Source => Array_Type9'(1, 2, 3, 4, 5, 6, 7, 8, 9), Item => 10);
Run_Search (Source => Array_Type9'(1, 2, 3, 4, 5, 6, 7, 8, 9), Item => 1);
Run_Search (Source => Array_Type9'(1, 2, 3, 4, 5, 6, 7, 8, 9), Item => 6);
end Test_Binary_Search;

View file

@ -0,0 +1,20 @@
const func integer: binarySearchIterative (in array elemType: arr, in elemType: aKey) is func
result
var integer: result is 0;
local
var integer: low is 1;
var integer: high is 0;
var integer: middle is 0;
begin
high := length(arr);
while result = 0 and low <= high do
middle := low + (high - low) div 2;
if aKey < arr[middle] then
high := pred(middle);
elsif aKey > arr[middle] then
low := succ(middle);
else
result := middle;
end if;
end while;
end func;

View file

@ -0,0 +1,16 @@
const func integer: binarySearch (in array elemType: arr, in elemType: aKey, in integer: low, in integer: high) is func
result
var integer: result is 0;
begin
if low <= high then
result := (low + high) div 2;
if aKey < arr[result] then
result := binarySearch(arr, aKey, low, pred(result)); # search left
elsif aKey > arr[result] then
result := binarySearch(arr, aKey, succ(result), high); # search right
end if;
end if;
end func;
const func integer: binarySearchRecursive (in array elemType: arr, in elemType: aKey) is
return binarySearch(arr, aKey, 1, length(arr));

View file

@ -0,0 +1,17 @@
fun binary_search cmp (key, arr) =
let
fun aux slice =
if ArraySlice.isEmpty slice then
NONE
else
let
val mid = ArraySlice.length slice div 2
in
case cmp (ArraySlice.sub (slice, mid), key)
of LESS => aux (ArraySlice.subslice (slice, mid+1, NONE))
| GREATER => aux (ArraySlice.subslice (slice, 0, SOME mid))
| EQUAL => SOME (#2 (ArraySlice.base slice) + mid)
end
in
aux (ArraySlice.full arr)
end

View file

@ -0,0 +1,18 @@
splitter() {
a=$1; s=$2; l=$3; r=$4;
mid=$(expr ${#a[*]} / 2);
echo $s ${a[*]:0:$mid} > $l
echo $(($mid + $s)) ${a[*]:$mid} > $r
}
bsearch() {
(to=$1; read s arr; a=($arr);
test ${#a[*]} -gt 1 && (splitter $a $s >(bsearch $to) >(bsearch $to)) || (test "$a" -eq "$to" && echo $a at $s)
)
}
binsearch() {
(read arr; echo "0 $arr" | bsearch $1)
}
echo "1 2 3 4 6 7 8 9" | binsearch 6

View file

@ -0,0 +1,17 @@
Public Function BinarySearch(a, value, low, high)
'search for "value" in ordered array a(low..high)
'return index point if found, -1 if not found
If high < low Then
BinarySearch = -1 'not found
Exit Function
End If
midd = low + Int((high - low) / 2) ' "midd" because "Mid" is reserved in VBA
If a(midd) > value Then
BinarySearch = BinarySearch(a, value, low, midd - 1)
ElseIf a(midd) < value Then
BinarySearch = BinarySearch(a, value, midd + 1, high)
Else
BinarySearch = midd
End If
End Function

View file

@ -0,0 +1,13 @@
Public Sub testBinarySearch(n)
Dim a(1 To 100)
'create an array with values = multiples of 10
For i = 1 To 100: a(i) = i * 10: Next
Debug.Print BinarySearch(a, n, LBound(a), UBound(a))
End Sub
Public Sub stringtestBinarySearch(w)
'uses BinarySearch with a string array
Dim a
a = Array("AA", "Maestro", "Mario", "Master", "Mattress", "Mister", "Mistress", "ZZ")
Debug.Print BinarySearch(a, w, LBound(a), UBound(a))
End Sub

View file

@ -0,0 +1,19 @@
Public Function BinarySearch2(a, value)
'search for "value" in array a
'return index point if found, -1 if not found
low = LBound(a)
high = UBound(a)
Do While low <= high
midd = low + Int((high - low) / 2)
If a(midd) = value Then
BinarySearch2 = midd
Exit Function
ElseIf a(midd) > value Then
high = midd - 1
Else
low = midd + 1
End If
Loop
BinarySearch2 = -1 'not found
End Function

View file

@ -0,0 +1,30 @@
// Main program for testing BINARY_SEARCH
#3 = Get_Num("Value to search: ")
EOF
#2 = Cur_Line // hi
#1 = 1 // lo
Call("BINARY_SEARCH")
Message("Value ") Num_Type(#3, NOCR)
if (Return_Value < 1) {
Message(" not found\n")
} else {
Message(" found at index ") Num_Type(Return_Value)
}
return
:BINARY_SEARCH:
while (#1 <= #2) {
#12 = (#1 + #2) / 2
Goto_Line(#12)
#11 = Num_Eval()
if (#3 == #11) {
return(#12) // found
} else {
if (#3 < #11) {
#2 = #12-1
} else {
#1 = #12+1
}
}
}
return(0) // not found

View file

@ -0,0 +1,18 @@
Function BinarySearch(ByVal A() As Integer, ByVal value As Integer) As Integer
Dim low As Integer = 0
Dim high As Integer = A.Length - 1
Dim middle As Integer = 0
While low <= high
middle = (low + high) / 2
If A(middle) > value Then
high = middle - 1
ElseIf A(middle) < value Then
low = middle + 1
Else
Return middle
End If
End While
Return Nothing
End Function

View file

@ -0,0 +1,17 @@
Function BinarySearch(ByVal A() As Integer, ByVal value As Integer, ByVal low As Integer, ByVal high As Integer) As Integer
Dim middle As Integer = 0
If high < low Then
Return Nothing
End If
middle = (low + high) / 2
If A(middle) > value Then
Return BinarySearch(A, value, low, middle - 1)
ElseIf A(middle) < value Then
Return BinarySearch(A, value, middle + 1, high)
Else
Return middle
End If
End Function