Binary search: Difference between revisions
→REXX: Refurbished (and corrected)
Basicgames (talk | contribs) |
Walterpachl (talk | contribs) (→REXX: Refurbished (and corrected)) |
||
Line 6,489:
}
}</syntaxhighlight>
=={{header|REXX}}==
=={{header|REXX}}==
===recursive version===
Incidentally, REXX doesn't care if the values in the list are integers (or even numbers), as long as they're in order.
<br><br>(includes the extra credit)
<syntaxhighlight lang="rexx"></
/*REXX program finds a value in a list of integers using an iterative binary search.*/
@= 3 7 13 19 23 31 43 47 61 73 83 89 103 109 113 131 139 151 167 181,▼
list=3 7
449 463 467 491 503 509 523 547 571 577 601 619 643 647 661 677 683 691 709,
743 761 773 797 811 823 829 839 859 863 883 887 911 919 941 953 971 983 1013
If needle=='' Then
exit /*stick a fork in it, we're all done. */▼
▲ low= 1
▲high= words(@)
If loc==-1 Then
▲ loc= binarySearch(low, high)
Exit
/*---------------------------------------------------------------------*/
exit /*stick a fork in it, we're all done. */▼
binarysearch: Procedure Expose list needle
Parse Arg i_low,i_high
else say ? ' is in the list, its index is: ' loc▼
Return-1
exit /*stick a fork in it, we're all done. */▼
Select
When y=needle Then
▲ if high<low then return -1 /*the item wasn't found in the @ list. */
Return i_mid
▲ mid= (low + high) % 2 /*calculate the midpoint in the list. */
When y>needle Then
▲ y= word(@, mid) /*obtain the midpoint value in the list*/
Return binarysearch(i_low,i_mid-1)
Otherwise
Return binarysearch(i_mid+1,i_high)
End
exit: Say arg(1)
{{out|output|text= when using the input of: <tt> 499.1 </tt>}}
▲499.1 wasn't found in the list.
<pre>619 is in the list, its index is: 53.</pre>
▲{{out|output|text= when using the input of: <tt> 499 </tt>}}
===iterative version===
(includes the extra credit)
<syntaxhighlight lang="rexx">/* REXX program finds a value in a list of integers */
/* using an iterative binary search. */
229 233 241 271 283 293 313 317 337 349 353 359 383 389 401 409 421 433 443,
449 463 467 491 503 509 523 547 571 577 601 619 643 647 661 677 683 691 709,
743 761 773 797 811 823 829 839 859 863 883 887 911 919 941 953 971 983 1013
/* list: a list of some low weak primes. */
Parse Arg needle /* get a number to be looked for */
If needle=="" Then
Call exit "***error*** no argument specified."
low=1
high=words(list)
Do While low<=high
mid=(low+high)%2
y=word(list,mid)
Select
When y=needle Then
high=mid-1 /* set upper nound */
End
End
Call exit needle "wasn't found in the list."
exit: Say arg(1) </syntaxhighlight>
▲499 is in the list, its index is: 41
{{out|output|text= when using the input of: <tt> -314 </tt>}}
<pre>-314 wasn't found in the list.
</pre>
{{out|output|text= when using the input of: <tt> 619 </tt>}}
<pre>619 is in the list, its index is: 53.</pre>
===iterative version===
|