task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #Phixmonti | Phixmonti | 6 var a 3 var b
def tab
9 tochar print
enddef
def printBits
8 int>bit reverse print nl
enddef
a print " = " print tab a printBits
b print " = " print tab b printBits
tab "------------------------" print nl
"AND = " print tab a b bitand printBits
"OR = " print tab a b bitor printBits
"XOR = " print tab a b bitxor printBits
"NOT = " print tab a bitnot printBits |
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #Logo | Logo | to bsearch :value :a :lower :upper
if :upper < :lower [output []]
localmake "mid int (:lower + :upper) / 2
if item :mid :a > :value [output bsearch :value :a :lower :mid-1]
if item :mid :a < :value [output bsearch :value :a :mid+1 :upper]
output :mid
end |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #Free_Pascal | Free Pascal | program binaryDigits(input, output, stdErr);
{$mode ISO}
function binaryNumber(const value: nativeUInt): shortString;
const
one = '1';
var
representation: shortString;
begin
representation := binStr(value, bitSizeOf(value));
// strip leading zeroes, if any; NB: mod has to be ISO compliant
delete(representation, 1, (pos(one, representation)-1) mod bitSizeOf(value));
// traditional Pascal fashion:
// assign result to the (implicitely existent) variable
// that is named like the function’s name
binaryNumber := representation;
end;
begin
writeLn(binaryNumber(5));
writeLn(binaryNumber(50));
writeLn(binaryNumber(9000));
end. |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #PHP | PHP | function bitwise($a, $b)
{
function zerofill($a,$b) {
if($a>=0) return $a>>$b;
if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with "if($b==0) return $a;" if you need $b=0 to mean that nothing happens
return ((~$a)>>$b)^(0x7fffffff>>($b-1));
echo '$a AND $b: ' . $a & $b . '\n';
echo '$a OR $b: ' . $a | $b . '\n';
echo '$a XOR $b: ' . $a ^ $b . '\n';
echo 'NOT $a: ' . ~$a . '\n';
echo '$a << $b: ' . $a << $b . '\n'; // left shift
echo '$a >> $b: ' . $a >> $b . '\n'; // arithmetic right shift
echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift
} |
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #Lolcode | Lolcode |
HAI 1.2
CAN HAS STDIO?
VISIBLE "HAI WORLD!!!1!"
VISIBLE "IMA GONNA SHOW U BINA POUNCE NAO"
I HAS A list ITZ A BUKKIT
list HAS A index0 ITZ 2
list HAS A index1 ITZ 3
list HAS A index2 ITZ 5
list HAS A index3 ITZ 7
list HAS A index4 ITZ 8
list HAS A index5 ITZ 9
list HAS A index6 ITZ 12
list HAS A index7 ITZ 20
BTW Method to access list by index number aka: list[index4]
HOW IZ list access YR indexNameNumber
FOUND YR list'Z SRS indexNameNumber
IF U SAY SO
BTW Method to print the array on the same line
HOW IZ list printList
I HAS A allList ITZ ""
I HAS A indexNameNumber ITZ "index0"
I HAS A index ITZ 0
IM IN YR walkingLoop UPPIN YR index TIL BOTH SAEM index AN 8
indexNameNumber R SMOOSH "index" index MKAY
allList R SMOOSH allList " " list IZ access YR indexNameNumber MKAY MKAY
IM OUTTA YR walkingLoop
FOUND YR allList
IF U SAY SO
VISIBLE "WE START WIF BUKKIT LIEK DIS: " list IZ printList MKAY
I HAS A target ITZ 12
VISIBLE "AN TARGET LIEK DIS: " target
VISIBLE "AN NAO 4 MAGI"
HOW IZ I binaPounce YR list AN YR listLength AN YR target
I HAS A left ITZ 0
I HAS A right ITZ DIFF OF listLength AN 1
IM IN YR whileLoop
BTW exit while loop when left > right
DIFFRINT left AN SMALLR OF left AN right
O RLY?
YA RLY
GTFO
OIC
I HAS A mid ITZ QUOSHUNT OF SUM OF left AN right AN 2
I HAS A midIndexname ITZ SMOOSH "index" mid MKAY
BTW if target == list[mid] return mid
BOTH SAEM target AN list IZ access YR midIndexname MKAY
O RLY?
YA RLY
FOUND YR mid
OIC
BTW if target < list[mid] right = mid - 1
DIFFRINT target AN BIGGR OF target AN list IZ access YR midIndexname MKAY
O RLY?
YA RLY
right R DIFF OF mid AN 1
OIC
BTW if target > list[mid] left = mid + 1
DIFFRINT target AN SMALLR OF target AN list IZ access YR midIndexname MKAY
O RLY?
YA RLY
left R SUM OF mid AN 1
OIC
IM OUTTA YR whileLoop
FOUND YR -1
IF U SAY SO
BTW call binary search on target here and print the index
I HAS A targetIndex ITZ I IZ binaPounce YR list AN YR 8 AN YR target MKAY
VISIBLE "TARGET " target " IZ IN BUKKIT " targetIndex
VISIBLE "WE HAS TEH TARGET!!1!!"
VISIBLE "I CAN HAS UR CHEEZBURGER NAO?"
KTHXBYE
end |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #FreeBASIC | FreeBASIC |
' FreeBASIC v1.05.0 win64
Dim As String fmt = "#### -> &"
Print Using fmt; 5; Bin(5)
Print Using fmt; 50; Bin(50)
Print Using fmt; 9000; Bin(9000)
Print
Print "Press any key to exit the program"
Sleep
End
|
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #PicoLisp | PicoLisp | : (& 6 3)
-> 2
: (& 7 3 1)
-> 1 |
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #Lua | Lua | function binarySearch (list,value)
local low = 1
local high = #list
while low <= high do
local mid = math.floor((low+high)/2)
if list[mid] > value then high = mid - 1
elseif list[mid] < value then low = mid + 1
else return mid
end
end
return false
end |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #Frink | Frink |
9000 -> binary
9000 -> base2
base2[9000]
base[9000, 2]
|
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #Pike | Pike |
void bitwise(int a, int b)
{
write("a and b: %d\n", a & b);
write("a or b: %d\n", a | b);
write("a xor b: %d\n", a ^ b);
write("not a: %d\n", ~a);
write("a << b: 0x%x\n", a << b);
write("a >> b: %d\n", a >> b);
// ints in Pike do not overflow, if a particular size of the int
// is desired then cap it with an AND operation
write("a << b & 0xffffffff (32bit cap): 0x%x\n",
a << b & 0xffffffff);
}
void main()
{
bitwise(255, 30);
}
|
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #M2000_Interpreter | M2000 Interpreter |
\\ binary search
const N=10
Dim A(0 to N-1)
A(0):=1,2,3,4,5,6,8,9,10,11
Print Len(A())=10
Function BinarySearch(&A(), aValue) {
def long mid, lo, hi
def boolean ok=False
let lo=0, hi=Len(A())-1
While lo<=hi
mid=(lo+hi)/2
if A(mid)>aValue Then
hi=mid-1
Else.if A(mid)<aValue Then
lo=mid+1
Else
=mid
ok=True
exit
End if
End While
if not ok then =-lo-1
}
For i=0 to 12
Rem Print "Search for value:";i
where= BinarySearch(&A(), i)
if where>=0 then
Print "found i at index: ";where
else
where=-where-1
if where<len(A()) then
Print "Not found, we can insert it at index: ";where
Dim A(len(A())+1) ' redim
stock A(where) keep len(A())-where-1, A(where+1) 'move items up
A(where)=i ' insert value
Else
Print "Not found, we can append to array at index: ";where
Dim A(len(A())+1) ' redim
A(where)=i ' insert value
End If
end if
next i
Print Len(A())=13
Print A()
|
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #FunL | FunL | for n <- [5, 50, 9000, 9000000000]
println( n, bin(n) ) |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #PL.2FI | PL/I | /* PL/I can perform bit operations on binary integers. */
k = iand(i,j);
k = ior(i,j);
k = inot(i,j);
k = ieor(i,j);
k = isll(i,n); /* unsigned shifts i left by n places. */
k = isrl(i,n); /* unsigned shifts i right by n places. */
k = lower2(i, n); /* arithmetic right shift i by n places. */
k = raise2(i, n); /* arithmetic left shift i by n places. */
/* PL/I can also perform boolean operations on bit strings */
/* of any length: */
declare (s, t, u) bit (*);
u = s & t; /* logical and */
u = s | t; /* logical or */
u = ^ s; /* logical not */
u = s ^ t; /* exclusive or */
/* Built-in rotate functions are not available. */
/* They can be readily implemented by the user, though: */
u = substr(s, length(s), 1) || substr(s, 1, length(s)-1); /* implements rotate right. */
u = substr(s, 2) || substr(s, 1, 1); /* implements rotate left. */
|
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #M4 | M4 | define(`notfound',`-1')dnl
define(`midsearch',`ifelse(defn($1[$4]),$2,$4,
`ifelse(eval(defn($1[$4])>$2),1,`binarysearch($1,$2,$3,decr($4))',`binarysearch($1,$2,incr($4),$5)')')')dnl
define(`binarysearch',`ifelse(eval($4<$3),1,notfound,`midsearch($1,$2,$3,eval(($3+$4)/2),$4)')')dnl
dnl
define(`setrange',`ifelse(`$3',`',$2,`define($1[$2],$3)`'setrange($1,incr($2),shift(shift(shift($@))))')')dnl
define(`asize',decr(setrange(`a',1,1,3,5,7,11,13,17,19,23,29)))dnl
dnl
binarysearch(`a',5,1,asize)
binarysearch(`a',8,1,asize) |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #Futhark | Futhark |
fun main(x: i32): i64 =
loop (out = 0i64) = for i < 32 do
let digit = (x >> (31-i)) & 1
let out = (out * 10i64) + i64(digit)
in out
in out
|
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #Pop11 | Pop11 | define bitwise(a, b);
printf(a && b, 'a and b = %p\n');
printf(a || b, 'a or b = %p\n');
printf(a ||/& b, 'a xor b = %p\n');
printf(~~ a, 'not a = %p\n');
printf(a << b, 'left shift of a by b = %p\n');
printf(a >> b, 'arithmetic right shift of a by b = %p\n');
enddefine; |
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #Maple | Maple | BinarySearch := proc( A, value, low, high )
description "recursive binary search";
if high < low then
FAIL
else
local mid := iquo( high + low, 2 );
if A[ mid ] > value then
thisproc( A, value, low, mid - 1 )
elif A[ mid ] < value then
thisproc( A, value, mid + 1, high )
else
mid
end if
end if
end proc: |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #Gambas | Gambas | Public Sub Main()
Dim siBin As Short[] = [5, 50, 9000]
Dim siCount As Short
For siCount = 0 To siBin.Max
Print Bin(siBin[siCount])
Next
End |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #PowerShell | PowerShell | $X -band $Y
$X -bor $Y
$X -bxor $Y
-bnot $X |
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | BinarySearchRecursive[x_List, val_, lo_, hi_] :=
Module[{mid = lo + Round@((hi - lo)/2)},
If[hi < lo, Return[-1]];
Return[
Which[x[[mid]] > val, BinarySearchRecursive[x, val, lo, mid - 1],
x[[mid]] < val, BinarySearchRecursive[x, val, mid + 1, hi],
True, mid]
];
] |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #Go | Go | package main
import (
"fmt"
)
func main() {
for i := 0; i < 16; i++ {
fmt.Printf("%b\n", i)
}
} |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #PureBasic | PureBasic | Procedure Bitwise(a, b)
Debug a & b ; And
Debug a | b ;Or
Debug a ! b ; XOr
Debug ~a ;Not
Debug a << b ; shift left
Debug a >> b ; arithmetic shift right
; Logical shift right and rotates are not available
; You can of use inline ASM to achieve this:
Define Temp
; logical shift right
!mov edx, dword [p.v_a]
!mov ecx, dword [p.v_b]
!shr edx, cl
!mov dword [p.v_Temp], edx
Debug Temp
; rotate left
!mov edx, dword [p.v_a]
!mov ecx, dword [p.v_b]
!rol edx, cl
!mov dword [p.v_Temp], edx
Debug Temp
; rotate right
!mov edx, dword [p.v_a]
!mov ecx, dword [p.v_b]
!ror edx, cl
!mov dword [p.v_Temp], edx
Debug Temp
EndProcedure |
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #MATLAB | MATLAB | function mid = binarySearchRec(list,value,low,high)
if( high < low )
mid = [];
return
end
mid = floor((low + high)/2);
if( list(mid) > value )
mid = binarySearchRec(list,value,low,mid-1);
return
elseif( list(mid) < value )
mid = binarySearchRec(list,value,mid+1,high);
return
else
return
end
end |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #Groovy | Groovy | print '''
n binary
----- ---------------
'''
[5, 50, 9000].each {
printf('%5d %15s\n', it, Integer.toBinaryString(it))
} |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #Python | Python | def bitwise_built_ins(width, a, b):
mask = (1 << width) - 1
print(f"""\
AND: 0b{a :0{width}b}
& 0b{b :0{width}b}
= 0b{(a & b) & mask :0{width}b}
OR: 0b{a :0{width}b}
| 0b{b :0{width}b}
= 0b{(a | b) & mask :0{width}b}
XOR: 0b{a :0{width}b}
^ 0b{b :0{width}b}
= 0b{(a ^ b) & mask :0{width}b}
NOT: ~ 0b{a :0{width}b}
= 0b{(~a) & mask :0{width}b}
SHIFTS
RIGHT: 0b{a :0{width}b} >> 1
= 0b{(a >> 1) & mask :0{width}b}
LEFT: 0b{a :0{width}b} << 1
= 0b{(a << 1) & mask :0{width}b}
""")
def rotr(width, a, n):
"Rotate a, n times to the right"
if n < 0:
return rotl(width, a, -n)
elif n == 0:
return a
else:
mask = (1 << width) - 1
a, n = a & mask, n % width
return ((a >> n) # top moved down
| ((a & ((1 << n) - 1)) # Bottom masked...
<< (width - n))) # ... then moved up
def rotl(width, a, n):
"Rotate a, n times to the left"
if n < 0:
return rotr(width, a, -n)
elif n == 0:
return a
else:
mask = (1 << width) - 1
a, n = a & mask, n % width
return (((a << n) & mask) # bottom shifted up and masked
| (a >> (width - n))) # Top moved down
def asr(width, a, n):
"Arithmetic shift a, n times to the right. (sign preserving)."
mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)
if n < 0:
return (a << -n) & mask
elif n == 0:
return a
elif n >= width:
return mask if a & top_bit_mask else 0
else:
a = a & mask
if a & top_bit_mask: # Sign bit set?
signs = (1 << n) - 1
return a >> n | (signs << width - n)
else:
return a >> n
def helper_funcs(width, a):
mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)
aa = a | top_bit_mask # a with top bit set
print(f"""\
ROTATIONS
RIGHT: rotr({width}, 0b{a :0{width}b}, 1)
= 0b{rotr(width, a, 1) :0{width}b}
rotr({width}, 0b{a :0{width}b}, 2)
= 0b{rotr(width, a, 2) :0{width}b}
rotr({width}, 0b{a :0{width}b}, 4)
= 0b{rotr(width, a, 4) :0{width}b}
LEFT: rotl({width}, 0b{a :0{width}b}, 1)
= 0b{rotl(width, a, 1) :0{width}b}
rotl({width}, 0b{a :0{width}b}, 2)
= 0b{rotl(width, a, 2) :0{width}b}
rotl({width}, 0b{a :0{width}b}, 4)
= 0b{rotl(width, a, 4) :0{width}b}
SIGN-EXTENDING ARITHMETIC SHIFT RIGHT
asr({width}, 0b{a :0{width}b}, 1)
= 0b{asr(width, a, 1) :0{width}b}
asr({width}, 0b{aa :0{width}b}, 1)
= 0b{asr(width, aa, 1) :0{width}b}
asr({width}, 0b{a :0{width}b}, 2)
= 0b{asr(width, a, 2) :0{width}b}
asr({width}, 0b{aa :0{width}b}, 2)
= 0b{asr(width, aa, 2) :0{width}b}
asr({width}, 0b{a :0{width}b}, 4)
= 0b{asr(width, a, 4) :0{width}b}
asr({width}, 0b{aa :0{width}b}, 4)
= 0b{asr(width, aa, 4) :0{width}b}
""")
if __name__ == '__main__':
bitwise_built_ins(8, 27, 125)
helper_funcs(8, 27) |
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #Maxima | Maxima | find(L, n) := block([i: 1, j: length(L), k, p],
if n < L[i] or n > L[j] then 0 else (
while j - i > 0 do (
k: quotient(i + j, 2),
p: L[k],
if n < p then j: k - 1 elseif n > p then i: k + 1 else i: j: k
),
if n = L[i] then i else 0
)
)$
".."(a, b) := if a < b then makelist(i, i, a, b) else makelist(i, i, a, b, -1)$
infix("..")$
a: sublist(1 .. 1000, primep)$
find(a, 27);
0
find(a, 421);
82 |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #Haskell | Haskell | import Data.List
import Numeric
import Text.Printf
-- Use the built-in function showIntAtBase.
toBin n = showIntAtBase 2 ("01" !!) n ""
-- Implement our own version.
toBin1 0 = []
toBin1 x = (toBin1 $ x `div` 2) ++ (show $ x `mod` 2)
-- Or even more efficient (due to fusion) and universal implementation
toBin2 = foldMap show . reverse . toBase 2
toBase base = unfoldr modDiv
where modDiv 0 = Nothing
modDiv n = let (q, r) = (n `divMod` base) in Just (r, q)
printToBin n = putStrLn $ printf "%4d %14s %14s" n (toBin n) (toBin1 n)
main = do
putStrLn $ printf "%4s %14s %14s" "N" "toBin" "toBin1"
mapM_ printToBin [5, 50, 9000] |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #QB64 | QB64 |
' no rotations and shift aritmetic are available in QB64
' Bitwise operator in Qbasic and QB64
'AND (operator) the bit is set when both bits are set.
'EQV (operator) the bit is set when both are set or both are not set.
'IMP (operator) the bit is set when both are set or both are unset or the second condition bit is set.
'OR (operator) the bit is set when either bit is set.
'NOT (operator) the bit is set when a bit is not set and not set when a bit is set.
'XOR (operator) the bit is set when just one of the bits are set.
Print "Qbasic and QB64 operators"
Print " Operator 1 vs 1 1 vs 0 0 vs 0"
Print "AND", 1 And 1, 1 And 0, 0 And 0
Print " OR", 1 Or 1, 1 Or 0, 0 Or 0
Print "XOR", 1 Xor 1, 1 Xor 0, 0 Xor 0
Print "EQV", 1 Eqv 1, 1 Eqv 0, 0 Eqv 0
Print "IMP", 1 Imp 1, 1 Imp 0, 0 Imp 0
Print "NOT", Not 1, Not 0, Not -1, Not -2
Print "QB64 operators"
Dim As _Byte a, b, c
a = 1: b = 1: c = 1
For i = 1 To 4
Print a, b, c
Print _SHL(a, i), _SHL(b, i * 2), _SHL(c, i * 3)
Next
a = 16: b = 32: c = 8
For i = 1 To 4
Print a, b, c
Print _SHR(a, i), _SHR(b, i * 2), _SHR(c, i * 3)
Next
|
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #MAXScript | MAXScript | fn binarySearchIterative arr value =
(
lower = 1
upper = arr.count
while lower <= upper do
(
mid = (lower + upper) / 2
if arr[mid] > value then
(
upper = mid - 1
)
else if arr[mid] < value then
(
lower = mid + 1
)
else
(
return mid
)
)
-1
)
arr = #(1, 3, 4, 5, 6, 7, 8, 9, 10)
result = binarySearchIterative arr 6 |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #Icon_and_Unicon | Icon and Unicon | procedure main()
every i := 5 | 50 | 255 | 1285 | 9000 do
write(i," = ",binary(i))
end
procedure binary(n) #: return bitstring for integer n
static CT, cm, cb
initial {
CT := table() # cache table for results
cm := 2 ^ (cb := 4) # (tunable) cache modulus & pad bits
}
b := "" # build reversed bit string
while n > 0 do { # use cached result ...
if not (b ||:= \CT[1(i := n % cm, n /:= cm) ]) then {
CT[j := i] := "" # ...or start new cache entry
while j > 0 do
CT[i] ||:= "01"[ 1(1+j % 2, j /:= 2 )]
b ||:= CT[i] := left(CT[i],cb,"0") # finish cache with padding
}
}
return reverse(trim(b,"0")) # nothing extraneous
end |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #Quackery | Quackery | [ [] swap
64 times
[ 2 /mod
number$ rot join swap ]
drop
echo$ cr ] is echobin ( n --> )
[ 64 swap - rot64 ] is rrot64 ( n --> n )
[ say "first integer: " over echobin
say "second integer: " dup echobin
say "bitwise AND: " 2dup & echobin
say "bitwise OR: " 2dup | echobin
say "bitwise XOR: " 2dup ^ echobin
say "bitwise NOT: " over ~ echobin
say "bitwise LSHIFT: " 2dup << echobin
say "bitwise RSHIFT: " 2dup >> echobin
say "bitwise LROTATE: " 2dup rot64 echobin
say "bitwise RROTATE: " rrot64 echobin ] is task ( n n --> )
hex FFFFF hex F task |
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #MiniScript | MiniScript | binarySearch = function(A, value, low, high)
if high < low then return null
mid = floor((low + high) / 2)
if A[mid] > value then return binarySearch(A, value, low, mid-1)
if A[mid] < value then return binarySearch(A, value, mid+1, high)
return mid
end function |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #Idris | Idris | module Main
binaryDigit : Integer -> Char
binaryDigit n = if (mod n 2) == 1 then '1' else '0'
binaryString : Integer -> String
binaryString 0 = "0"
binaryString n = pack (loop n [])
where loop : Integer -> List Char -> List Char
loop 0 acc = acc
loop n acc = loop (div n 2) (binaryDigit n :: acc)
main : IO ()
main = do
putStrLn (binaryString 0)
putStrLn (binaryString 5)
putStrLn (binaryString 50)
putStrLn (binaryString 9000)
|
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #J | J | tobin=: -.&' '@":@#:
tobin 5
101
tobin 50
110010
tobin 9000
10001100101000 |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #R | R | # Since R 3.0.0, the base package provides bitwise operators, see ?bitwAnd
a <- 35
b <- 42
bitwAnd(a, b)
bitwOr(a, b)
bitwXor(a, b)
bitwNot(a)
bitwShiftL(a, 2)
bitwShiftR(a, 2) |
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #N.2Ft.2Froff | N/t/roff | .de end
..
.de array
. nr \\$1.c 0 1
. de \\$1.push end
. nr \\$1..\\\\n+[\\$1.c] \\\\$1
. end
. de \\$1.pushln end
. if \\\\n(.$>0 .\\$1.push \\\\$1
. if \\\\n(.$>1 \{ \
. shift
. \\$1.pushln \\\\$@
\}
. end
..
.
.de binarysearch
. nr min 1
. nr max \\n[\\$1.c]
. nr guess \\n[min]+\\n[max]/2
. while !\\n[\\$1..\\n[guess]]=\\$2 \{ \
. ie \\n[\\$1..\\n[guess]]<\\$2 .nr min \\n[guess]+1
. el .nr max \\n[guess]-1
.
. if \\n[min]>\\n[max] \{
. nr guess 0
. break
. \}
. nr guess \\n[min]+\\n[max]/2
. \}
\\n[guess]
..
.array a
.a.pushln 1 4 9 16 25 36 49 64 81 100 121 144
.binarysearch a 100
.br
.ie \n[guess]=0 The item \fBdoesn't exist\fP.
.el The item \fBdoes exist\fP.
|
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #Java | Java | public class Main {
public static void main(String[] args) {
System.out.println(Integer.toBinaryString(5));
System.out.println(Integer.toBinaryString(50));
System.out.println(Integer.toBinaryString(9000));
}
} |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #Racket | Racket |
#lang racket
(define a 255)
(define b 5)
(list (bitwise-and a b)
(bitwise-ior a b)
(bitwise-xor a b)
(bitwise-not a)
(arithmetic-shift a b) ; left shift
(arithmetic-shift a (- b))) ; right shift
|
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #Nim | Nim | import algorithm
let s = @[2,3,4,5,6,7,8,9,10,12,14,16,18,20,22,25,27,30]
echo binarySearch(s, 10) |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #JavaScript | JavaScript | function toBinary(number) {
return new Number(number)
.toString(2);
}
var demoValues = [5, 50, 9000];
for (var i = 0; i < demoValues.length; ++i) {
// alert() in a browser, wscript.echo in WSH, etc.
print(toBinary(demoValues[i]));
} |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #Raku | Raku | constant MAXINT = uint.Range.max;
constant BITS = MAXINT.base(2).chars;
# define rotate ops for the fun of it
multi sub infix:<⥁>(Int:D \a, Int:D \b) { :2[(a +& MAXINT).polymod(2 xx BITS-1).list.rotate(b).reverse] }
multi sub infix:<⥀>(Int:D \a, Int:D \b) { :2[(a +& MAXINT).polymod(2 xx BITS-1).reverse.list.rotate(b)] }
sub int-bits (Int $a, Int $b) {
say '';
say_bit "$a", $a;
say '';
say_bit "2's complement $a", +^$a;
say_bit "$a and $b", $a +& $b;
say_bit "$a or $b", $a +| $b;
say_bit "$a xor $b", $a +^ $b;
say_bit "$a unsigned shift right $b", ($a +& MAXINT) +> $b;
say_bit "$a signed shift right $b", $a +> $b;
say_bit "$a rotate right $b", $a ⥁ $b;
say_bit "$a shift left $b", $a +< $b;
say_bit "$a rotate left $b", $a ⥀ $b;
}
int-bits(7,2);
int-bits(-65432,31);
sub say_bit ($message, $value) {
printf("%30s: %{'0' ~ BITS}b\n", $message, $value +& MAXINT);
} |
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #Niue | Niue | 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) |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #Joy | Joy | HIDE
_ == [null] [pop] [2 div swap] [48 + putch] linrec
IN
int2bin == [null] [48 + putch] [_] ifte '\n putch
END |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #jq | jq | def binary_digits:
[ recurse( ./2 | floor; . > 0) % 2 ] | reverse | join("") ;
# The task:
(5, 50, 9000) | binary_digits |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #Red | Red | Red [Source: https://github.com/vazub/rosetta-red]
a: 10
b: 2
print [
pad "a =" 10 a newline
pad "b =" 10 b newline
pad "a AND b:" 10 a and b newline
pad "a OR b:" 10 a or b newline
pad "a XOR b:" 10 a xor b newline
pad "NOT a:" 10 complement a newline
pad "a >>> b:" 10 a >>> b newline
pad "a >> b:" 10 a >> b newline
pad "a << b:" 10 a << b newline
; there are no circular shift operators in Red
]
|
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #Objeck | Objeck | 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;
}
}
} |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #Julia | Julia | using Printf
for n in (0, 5, 50, 9000)
@printf("%6i → %s\n", n, string(n, base=2))
end
# with pad
println("\nwith pad")
for n in (0, 5, 50, 9000)
@printf("%6i → %s\n", n, string(n, base=2, pad=20))
end |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #Retro | Retro |
: bitwise ( ab- )
cr
over "a = %d\n" puts
dup "b = %d\n" puts
2over and "a and b = %d\n" puts
2over or "a or b = %d\n" puts
2over xor "a xor b = %d\n" puts
over not "not a = %d\n" puts
2over << "a << b = %d\n" puts
2over >> "a >> b = %d\n" puts
2drop ; |
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #Objective-C | Objective-C | #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[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()
{
@autoreleasepool {
NSArray *a = @[@1, @3, @4, @5, @6, @7, @8, @9, @10];
NSLog(@"6 is at position %d", [a binarySearch:@6]); // prints 4
}
return 0;
} |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #K | K | tobin: ,/$2_vs
tobin' 5 50 9000
("101"
"110010"
"10001100101000") |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #REXX | REXX | ╔═══════════════════════════════════════════════════════════════════════════════════════╗
║ Since REXX stores numbers (indeed, all values) as characters, it makes no sense to ║
║ "rotate" a value, since there aren't any boundaries for the value. I.E.: there ║
║ isn't any 32─bit word "container" or "cell" (for instance) to store an integer. ║
║ ║
║ Furthermore, since REXX numbers can be arbitrary precision, the concept of rotating ║
║ a number has no meaning. ║
╚═══════════════════════════════════════════════════════════════════════════════════════╝
|
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #OCaml | OCaml | 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 |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #Kotlin | Kotlin | // version 1.0.5-2
fun main(args: Array<String>) {
val numbers = intArrayOf(5, 50, 9000)
for (number in numbers) println("%4d".format(number) + " -> " + Integer.toBinaryString(number))
} |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #Ring | Ring |
x = 8
y = 2
see "x & y - Binary AND : " + (x & y) + nl
see "x | y - Binary OR : " + (x | y) + nl
see "x ^ y - Binary XOR : " + (x ^ y) +nl
see "~x - Binary Ones Complement : " + (~x) + nl
see "x << y - Binary Left Shift : " + (x << y) + nl
see "x >> y - Binary Right Shift : " + (x >> y) + nl
|
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #Octave | Octave | 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 |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #Lambdatalk | Lambdatalk |
{def dec2bin
{lambda {:dec}
{if {= :dec 0}
then 0
else {if {< :dec 2}
then 1
else {dec2bin {floor {/ :dec 2}}}{% :dec 2} }}}}
-> dec2bin
{dec2bin 5} -> 101
{dec2bin 5} -> 110010
{dec2bin 9000} -> 10001100101000
{S.map dec2bin 5 50 9000}
-> 101 110010 10001100101000
{S.map {lambda {:i} {br}:i -> {dec2bin :i}} 5 50 9000}
->
5 -> 101
50 -> 110010
9000 -> 10001100101000
|
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #RLaB | RLaB | >> x = int(3);
>> y = int(1);
>> z = x && y; printf("0x%08x\n",z); // logical 'and'
0x00000001
>> z = x || y; printf("0x%08x\n",z); // logical 'or'
0x00000003
>> z = !x; printf("0x%08x\n",z); // logical 'not'
0xfffffffc
>> i2 = int(2);
>> z = x * i2; printf("0x%08x\n",z); // left-shift is multiplication by 2 where both arguments are integers
0x00000006
>> z = x / i2; printf("0x%08x\n",z); // right-shift is division by 2 where both arguments are integers
0x00000001 |
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #Ol | Ol |
(define (binary-search value vector)
(let helper ((low 0)
(high (- (vector-length vector) 1)))
(unless (< high low)
(let ((middle (quotient (+ low high) 2)))
(cond
((> (vector-ref vector middle) value)
(helper low (- middle 1)))
((< (vector-ref vector middle) value)
(helper (+ middle 1) high))
(else middle))))))
(print
(binary-search 12 [1 2 3 4 5 6 7 8 9 10 11 12 13]))
; ==> 12
|
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #Lang5 | Lang5 | '%b '__number_format set
[5 50 9000] [3 1] reshape . |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #Robotic | Robotic |
input string "First value"
set "local1" to "input"
input string "Second value"
set "local2" to "input"
. ">>> is an arithmetic shift; >> is a logical shift"
[ "a AND b = ('local1' a 'local2')"
[ "a OR b = ('local1' o 'local2')"
[ "a XOR b = ('local1' x 'local2')"
[ "NOT a = (~'local1')"
[ "a << b = ('local1' << 'local2')"
[ "a >> b = ('local1' >> 'local2')"
[ "a >>> b = ('local1' >>> 'local2')"
end
. "Bitwise rotation is not natively supported"
|
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #ooRexx | ooRexx |
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
|
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #LFE | LFE |
(: io format '"~.2B~n~.2B~n~.2B~n" (list 5 50 9000))
|
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #Ruby | Ruby | def bitwise(a, b)
form = "%1$7s:%2$6d %2$016b"
puts form % ["a", a]
puts form % ["b", b]
puts form % ["a and b", a & b]
puts form % ["a or b ", a | b]
puts form % ["a xor b", a ^ b]
puts form % ["not a ", ~a]
puts form % ["a << b ", a << b] # left shift
puts form % ["a >> b ", a >> b] # arithmetic right shift
end
bitwise(14,3) |
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #Oz | Oz | 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}} |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #Liberty_BASIC | Liberty BASIC | for a = 0 to 16
print a;"=";dec2bin$(a)
next
a=50:print a;"=";dec2bin$(a)
a=254:print a;"=";dec2bin$(a)
a=9000:print a;"=";dec2bin$(a)
wait
function dec2bin$(num)
if num=0 then dec2bin$="0":exit function
while num>0
dec2bin$=str$(num mod 2)+dec2bin$
num=int(num/2)
wend
end function
|
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #Rust | Rust | fn main() {
let a: u8 = 105;
let b: u8 = 91;
println!("a = {:0>8b}", a);
println!("b = {:0>8b}", b);
println!("a | b = {:0>8b}", a | b);
println!("a & b = {:0>8b}", a & b);
println!("a ^ b = {:0>8b}", a ^ b);
println!("!a = {:0>8b}", !a);
println!("a << 3 = {:0>8b}", a << 3);
println!("a >> 3 = {:0>8b}", a >> 3);
} |
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #PARI.2FGP | PARI/GP | setsearch(s, n) |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #Little_Man_Computer | Little Man Computer |
// Little Man Computer, for Rosetta Code.
// Read numbers from user and display them in binary.
// Exit when input = 0.
input INP
BRZ zero
STA N
// Write number followed by '->'
OUT
LDA asc_hy
OTC
LDA asc_gt
OTC
// Find greatest power of 2 not exceeding N,
// and count how many digits will be output
LDA c1
STA pwr2
loop STA nrDigits
LDA N
SUB pwr2
SUB pwr2
BRP double
BRA part2 // jump out if next power of 2 would exceed N
double LDA pwr2
ADD pwr2
STA pwr2
LDA nrDigits
ADD c1
BRA loop
// Write the binary digits
part2 LDA N
SUB pwr2
set_diff STA diff
LDA asc_1 // first digit is always 1
wr_digit OTC // write digit
LDA nrDigits // count down the number of digits
SUB c1
BRZ input // if all digits done, loop for next number
STA nrDigits
// We now want to compare diff with pwr2/2.
// Since division is awkward in LMC, we compare 2*diff with pwr2.
LDA diff // diff := diff * 2
ADD diff
STA diff
SUB pwr2 // is diff >= pwr2 ?
BRP set_diff // yes, update diff and write '1'
LDA asc_0 // no, write '0'
BRA wr_digit
zero HLT // stop if input = 0
// Constants
c1 DAT 1
asc_hy DAT 45
asc_gt DAT 62
asc_0 DAT 48
asc_1 DAT 49
// Variables
N DAT
pwr2 DAT
nrDigits DAT
diff DAT
|
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #SAS | SAS | /* rotations are not available, but are easy to implement with the other bitwise operators */
data _null_;
a=105;
b=91;
c=bxor(a,b);
d=band(a,b);
e=bor(a,b);
f=bnot(a); /* on 32 bits */
g=blshift(a,1);
h=brshift(a,1);
put _all_;
run; |
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #Pascal | Pascal | function binary_search(element: real; list: array of real): integer;
var
l, m, h: integer;
begin
l := Low(list);
h := High(list);
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; |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #LLVM | LLVM | ; ModuleID = 'binary.c'
; source_filename = "binary.c"
; target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
; target triple = "x86_64-pc-windows-msvc19.21.27702"
; This is not strictly LLVM, as it uses the C library function "printf".
; LLVM does not provide a way to print values, so the alternative would be
; to just load the string into memory, and that would be boring.
; Additional comments have been inserted, as well as changes made from the output produced by clang such as putting more meaningful labels for the jumps
$"\01??_C@_03OFAPEBGM@?$CFs?6?$AA@" = comdat any
;--- String constant defintions
@"\01??_C@_03OFAPEBGM@?$CFs?6?$AA@" = linkonce_odr unnamed_addr constant [4 x i8] c"%s\0A\00", comdat, align 1
;--- The declaration for the external C printf function.
declare i32 @printf(i8*, ...)
;--- The declaration for the external C log10 function.
declare double @log10(double) #1
;--- The declaration for the external C malloc function.
declare noalias i8* @malloc(i64) #2
;--- The declaration for the external C free function.
declare void @free(i8*) #2
;----------------------------------------------------------
;-- Function that allocates a string with a binary representation of a number
define i8* @bin(i32) #0 {
;-- uint32_t x (local copy)
%2 = alloca i32, align 4
;-- size_t bits
%3 = alloca i64, align 8
;-- intermediate value
%4 = alloca i8*, align 8
;-- size_t i
%5 = alloca i64, align 8
store i32 %0, i32* %2, align 4
;-- x == 0, start determinig what value to initially store in bits
%6 = load i32, i32* %2, align 4
%7 = icmp eq i32 %6, 0
br i1 %7, label %just_one, label %calculate_logs
just_one:
br label %assign_bits
calculate_logs:
;-- log10((double) x)/log10(2) + 1
%8 = load i32, i32* %2, align 4
%9 = uitofp i32 %8 to double
;-- log10((double) x)
%10 = call double @log10(double %9) #3
;-- log10(2)
%11 = call double @log10(double 2.000000e+00) #3
;-- remainder of calculation
%12 = fdiv double %10, %11
%13 = fadd double %12, 1.000000e+00
br label %assign_bits
assign_bits:
;-- bits = (x == 0) ? 1 : log10((double) x)/log10(2) + 1;
;-- phi basically selects what the value to assign should be based on which basic block came before
%14 = phi double [ 1.000000e+00, %just_one ], [ %13, %calculate_logs ]
%15 = fptoui double %14 to i64
store i64 %15, i64* %3, align 8
;-- char *ret = malloc((bits + 1) * sizeof (char));
%16 = load i64, i64* %3, align 8
%17 = add i64 %16, 1
%18 = mul i64 %17, 1
%19 = call noalias i8* @malloc(i64 %18)
store i8* %19, i8** %4, align 8
store i64 0, i64* %5, align 8
br label %loop
loop:
;-- i < bits;
%20 = load i64, i64* %5, align 8
%21 = load i64, i64* %3, align 8
%22 = icmp ult i64 %20, %21
br i1 %22, label %loop_body, label %exit
loop_body:
;-- ret[bits - i - 1] = (x & 1) ? '1' : '0';
%23 = load i32, i32* %2, align 4
%24 = and i32 %23, 1
%25 = icmp ne i32 %24, 0
%26 = zext i1 %25 to i64
%27 = select i1 %25, i32 49, i32 48
%28 = trunc i32 %27 to i8
%29 = load i8*, i8** %4, align 8
%30 = load i64, i64* %3, align 8
%31 = load i64, i64* %5, align 8
%32 = sub i64 %30, %31
%33 = sub i64 %32, 1
%34 = getelementptr inbounds i8, i8* %29, i64 %33
store i8 %28, i8* %34, align 1
;-- x >>= 1;
%35 = load i32, i32* %2, align 4
%36 = lshr i32 %35, 1
store i32 %36, i32* %2, align 4
br label %loop_increment
loop_increment:
;-- i++;
%37 = load i64, i64* %5, align 8
%38 = add i64 %37, 1
store i64 %38, i64* %5, align 8
br label %loop
exit:
;-- ret[bits] = '\0';
%39 = load i8*, i8** %4, align 8
%40 = load i64, i64* %3, align 8
%41 = getelementptr inbounds i8, i8* %39, i64 %40
store i8 0, i8* %41, align 1
;-- return ret;
%42 = load i8*, i8** %4, align 8
ret i8* %42
}
;----------------------------------------------------------
;-- Entry point into the program
define i32 @main() #0 {
;-- 32-bit zero for the return
%1 = alloca i32, align 4
;-- size_t i, for tracking the loop index
%2 = alloca i64, align 8
;-- char* for the result of the bin call
%3 = alloca i8*, align 8
;-- initialize
store i32 0, i32* %1, align 4
store i64 0, i64* %2, align 8
br label %loop
loop:
;-- while (i < 20)
%4 = load i64, i64* %2, align 8
%5 = icmp ult i64 %4, 20
br i1 %5, label %loop_body, label %exit
loop_body:
;-- char *binstr = bin(i);
%6 = load i64, i64* %2, align 8
%7 = trunc i64 %6 to i32
%8 = call i8* @bin(i32 %7)
store i8* %8, i8** %3, align 8
;-- printf("%s\n", binstr);
%9 = load i8*, i8** %3, align 8
%10 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01??_C@_03OFAPEBGM@?$CFs?6?$AA@", i32 0, i32 0), i8* %9)
;-- free(binstr);
%11 = load i8*, i8** %3, align 8
call void @free(i8* %11)
br label %loop_increment
loop_increment:
;-- i++
%12 = load i64, i64* %2, align 8
%13 = add i64 %12, 1
store i64 %13, i64* %2, align 8
br label %loop
exit:
;-- return 0 (implicit)
%14 = load i32, i32* %1, align 4
ret i32 %14
}
attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #1 = { nounwind "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #2 = { "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #3 = { nounwind }
!llvm.module.flags = !{!0, !1}
!llvm.ident = !{!2}
!0 = !{i32 1, !"wchar_size", i32 2}
!1 = !{i32 7, !"PIC Level", i32 2}
!2 = !{!"clang version 6.0.1 (tags/RELEASE_601/final)"} |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #Scala | Scala | def bitwise(a: Int, b: Int) {
println("a and b: " + (a & b))
println("a or b: " + (a | b))
println("a xor b: " + (a ^ b))
println("not a: " + (~a))
println("a << b: " + (a << b)) // left shift
println("a >> b: " + (a >> b)) // arithmetic right shift
println("a >>> b: " + (a >>> b)) // unsigned right shift
println("a rot b: " + Integer.rotateLeft(a, b)) // Rotate Left
println("a rol b: " + Integer.rotateRight(a, b)) // Rotate Right
} |
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #Perl | Perl | sub binary_search {
my ($array_ref, $value, $left, $right) = @_;
while ($left <= $right) {
my $middle = int(($right + $left) >> 1);
if ($value == $array_ref->[$middle]) {
return $middle;
}
elsif ($value < $array_ref->[$middle]) {
$right = $middle - 1;
}
else {
$left = $middle + 1;
}
}
return -1;
} |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #Locomotive_Basic | Locomotive Basic | 10 PRINT BIN$(5)
20 PRINT BIN$(50)
30 PRINT BIN$(9000) |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #Scheme | Scheme | (import (rnrs arithmetic bitwise (6)))
(define (bitwise a b)
(display (bitwise-and a b))
(newline)
(display (bitwise-ior a b))
(newline)
(display (bitwise-xor a b))
(newline)
(display (bitwise-not a))
(newline)
(display (bitwise-arithmetic-shift-right a b))
(newline))
(bitwise 255 5) |
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #Phix | Phix | 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 -- found!
end if
end while
mid += c>0
return -mid -- where it would go, if inserted now
end function
|
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #LOLCODE | LOLCODE | HAI 1.3
HOW IZ I DECIMULBINUR YR DECIMUL
I HAS A BINUR ITZ ""
IM IN YR DUUH
BOTH SAEM DECIMUL AN SMALLR OF DECIMUL AN 0, O RLY?
YA RLY, GTFO
OIC
BINUR R SMOOSH MOD OF DECIMUL AN 2 BINUR MKAY
DECIMUL R MAEK QUOSHUNT OF DECIMUL AN 2 A NUMBR
IM OUTTA YR DUUH
FOUND YR BINUR
IF U SAY SO
VISIBLE I IZ DECIMULBINUR YR 5 MKAY
VISIBLE I IZ DECIMULBINUR YR 50 MKAY
VISIBLE I IZ DECIMULBINUR YR 9000 MKAY
KTHXBYE |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "bin32.s7i";
const proc: bitwise (in integer: a, in integer: b) is func
begin
writeln("a: " <& a radix 2 lpad0 32);
writeln("b: " <& b radix 2 lpad0 32);
writeln("integer operations:");
writeln("a << b: " <& a << b radix 2 lpad0 32); # left shift
writeln("a >> b: " <& a >> b radix 2 lpad0 32); # arithmetic right shift
end func;
const proc: bitwise (in bin32: a, in bin32: b) is func
begin
writeln("bin32 operations:");
writeln("a and b: " <& a & b radix 2 lpad0 32);
writeln("a or b: " <& a | b radix 2 lpad0 32);
writeln("a xor b: " <& a >< b radix 2 lpad0 32);
writeln("not a: " <& ~a radix 2 lpad0 32);
writeln("a << b: " <& a << ord(b) radix 2 lpad0 32); # left shift
writeln("a >> b: " <& a >> ord(b) radix 2 lpad0 32); # logical right shift
writeln("a rotL b: " <& rotLeft(a, ord(b)) radix 2 lpad0 32); # Rotate Left
writeln("a rolR b: " <& rotRight(a, ord(b)) radix 2 lpad0 32); # Rotate Right
end func;
const proc: main is func
begin
bitwise(65076, 6);
bitwise(bin32(65076), bin32(6));
end func; |
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #PHP | PHP | function binary_search( $array, $secret, $start, $end )
{
do
{
$guess = (int)($start + ( ( $end - $start ) / 2 ));
if ( $array[$guess] > $secret )
$end = $guess;
if ( $array[$guess] < $secret )
$start = $guess;
if ( $end < $start)
return -1;
} while ( $array[$guess] != $secret );
return $guess;
} |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #Lua | Lua | function dec2bin (n)
local bin = ""
while n > 0 do
bin = n % 2 .. bin
n = math.floor(n / 2)
end
return bin
end
print(dec2bin(5))
print(dec2bin(50))
print(dec2bin(9000)) |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #Sidef | Sidef | func bitwise(a, b) {
say ('a and b : ', a & b)
say ('a or b : ', a | b)
say ('a xor b : ', a ^ b)
say ('not a : ', ~a)
say ('a << b : ', a << b) # left shift
say ('a >> b : ', a >> b) # arithmetic right shift
}
bitwise(14,3) |
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #Picat | Picat | go =>
A = [2, 4, 6, 8, 9],
TestValues = [2,1,8,10,9,5],
foreach(Value in TestValues)
test(binary_search,A, Value)
end,
test(binary_search,[1,20,3,4], 5),
nl.
% Test with binary search predicate Search
test(Search,A,Value) =>
Ret = apply(Search,A,Value),
printf("A: %w Value:%d Ret: %d: ", A, Value, Ret),
if Ret == -1 then
println("The array is not sorted.")
elseif Ret == 0 then
printf("The value %d is not in the array.\n", Value)
else
printf("The value %d is found at position %d.\n", Value, Ret)
end.
binary_search(A, Value) = V =>
V1 = 0,
% we want a sorted array
if not sort(A) == A then
V1 := -1
else
Low = 1,
High = A.length,
Mid = 1,
Found = 0,
while (Found == 0, Low <= High)
Mid := (Low + High) // 2,
if A[Mid] > Value then
High := Mid - 1
elseif A[Mid] < Value then
Low := Mid + 1
else
V1 := Mid,
Found := 1
end
end
end,
V = V1.
|
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
Form 90, 40
Function BinFunc${
Dim Base 0, One$(16)
One$( 0 ) = "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"
=lambda$ One$() (x, oct as long=4, bypass as boolean=True) ->{
if oct>0 and oct<5 then {
oct=2*(int(4-oct) mod 4+1)-1
} Else oct=1
hx$ = Hex$(x, 4 )
Def Ret$
If Bypass then {
For i= oct to len(hx$)
if bypass Then if Mid$(hx$, i, 1 )="0" Else bypass=false
If bypass and i<>Len(hx$) Then Continue
Ret$ += One$( EVal( "0x" + Mid$(hx$, i, 1 ) ) )
Next i
oct=instr(Ret$, "1")
if oct=0 then {
Ret$="0"
} Else Ret$=mid$(Ret$, oct)
} Else {
For i= oct to len(hx$)
Ret$ += One$( EVal( "0x" + Mid$(hx$, i, 1 ) ) )
Next i
}
=Ret$
}
}
Bin$=BinFunc$()
Stack New {
Data 9, 50, 9000
While not empty {
Read x
Print Format$("The decimal value {0::-10} should produce an output of {1:-32}",x, Bin$(x) )
}
}
Stack New {
Data 9, 50, 9000
While not empty {
Read x
Print Format$("The decimal value {0::-10} should produce an output of {1:-32}",x, Bin$(x,,false) )
}
}
Stack New {
Data 9, 50, 9000
While not empty {
Read x
Print Bin$(x)
}
}
}
Checkit
|
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #Simula | Simula | BEGIN
COMMENT TO MY KNOWLEDGE SIMULA DOES NOT SUPPORT BITWISE OPERATIONS SO WE MUST WRITE PROCEDURES FOR THE JOB ;
INTEGER WORDSIZE;
WORDSIZE := 32;
BEGIN
PROCEDURE TOBITS(N,B); INTEGER N; BOOLEAN ARRAY B;
BEGIN
INTEGER I,BITN;
FOR I := WORDSIZE-1 STEP -1 UNTIL 0 DO BEGIN
BITN := MOD(N,2); B(I) := BITN<>0; N := N // 2;
END;
END TOBITS;
INTEGER PROCEDURE FROMBITS(B); BOOLEAN ARRAY B;
BEGIN
INTEGER I, RESULT;
FOR I := 0 STEP 1 UNTIL WORDSIZE-1 DO
RESULT := 2 * RESULT + (IF B(I) THEN 1 ELSE 0);
FROMBITS := RESULT;
END FROMBITS;
INTEGER PROCEDURE BITOP(A,B,F);
INTEGER A,B;
PROCEDURE F IS BOOLEAN PROCEDURE F(A,B); BOOLEAN A,B;;
BEGIN
INTEGER I;
BOOLEAN ARRAY BA(0:WORDSIZE-1);
BOOLEAN ARRAY BB(0:WORDSIZE-1);
TOBITS(A,BA);
TOBITS(B,BB);
FOR I := 0 STEP 1 UNTIL WORDSIZE-1 DO BA(I) := F(BA(I),BB(I));
BITOP := FROMBITS(BA);
END BITOP;
INTEGER PROCEDURE BITUOP(A,F);
INTEGER A;
PROCEDURE F IS BOOLEAN PROCEDURE F(A); BOOLEAN A;;
BEGIN
INTEGER I;
BOOLEAN ARRAY BA(0:WORDSIZE-1);
TOBITS(A,BA);
FOR I := 0 STEP 1 UNTIL WORDSIZE-1 DO BA(I) := F(BA(I));
BITUOP := FROMBITS(BA);
END BITUOP;
BOOLEAN PROCEDURE OPAND(A,B); BOOLEAN A,B; OPAND := A AND B;
INTEGER PROCEDURE BITAND(A,B); INTEGER A,B; BITAND := BITOP(A,B,OPAND);
BOOLEAN PROCEDURE OPOR(A,B); BOOLEAN A,B; OPOR := A OR B;
INTEGER PROCEDURE BITOR(A,B); INTEGER A,B; BITOR := BITOP(A,B,OPOR);
BOOLEAN PROCEDURE OPXOR(A,B); BOOLEAN A,B; OPXOR := (A AND NOT B) OR (NOT A AND B);
INTEGER PROCEDURE BITXOR(A,B); INTEGER A,B; BITXOR := BITOP(A,B,OPXOR);
BOOLEAN PROCEDURE OPNOT(A); BOOLEAN A; OPNOT := NOT A;
INTEGER PROCEDURE BITNOT(A); INTEGER A; BITNOT := BITUOP(A,OPNOT);
INTEGER PROCEDURE BITSHL(A,B); INTEGER A,B;
BEGIN
IF B < 0 THEN A := BITSHR(A,-B)
ELSE WHILE B > 0 DO BEGIN A := 2 * A; B := B-1; END;
BITSHL := A;
END BITSHL;
INTEGER PROCEDURE BITSHR(A,B); INTEGER A,B;
BEGIN
IF B < 0 THEN A := BITSHL(A,-B)
ELSE WHILE B > 0 DO BEGIN A := A // 2; B := B-1; END;
BITSHR := A;
END BITSHR;
INTEGER PROCEDURE BITROTR(A,B); INTEGER A,B;
BEGIN
INTEGER I,J;
BOOLEAN ARRAY BA(0:WORDSIZE-1);
BOOLEAN ARRAY BB(0:WORDSIZE-1);
TOBITS(A,BA);
FOR I := 0 STEP 1 UNTIL WORDSIZE-1 DO BEGIN
J := MOD(I + B, WORDSIZE); BB(J) := BA(I);
END;
BITROTR := FROMBITS(BB);
END BITROTR;
INTEGER PROCEDURE BITROTL(A,B); INTEGER A,B;
BITROTL := BITROTR(A,-B);
PROCEDURE BITWISE(A,B); INTEGER A,B;
BEGIN
OUTTEXT("A AND B : "); OUTINT(BITAND(A,B),0); OUTIMAGE;
OUTTEXT("A OR B : "); OUTINT(BITOR (A,B),0); OUTIMAGE;
OUTTEXT("A XOR B : "); OUTINT(BITXOR(A,B),0); OUTIMAGE;
OUTTEXT("NOT A : "); OUTINT(BITNOT(A), 0); OUTIMAGE;
OUTTEXT("A << B : "); OUTINT(BITSHL(A,B),0); OUTIMAGE; ! LEFT SHIFT ;
OUTTEXT("A >> B : "); OUTINT(BITSHR(A,B),0); OUTIMAGE; ! ARITHMETIC RIGHT SHIFT ;
OUTTEXT("A ROTL B : "); OUTINT(BITROTL(A,B),0); OUTIMAGE; ! ROTATE LEFT ;
OUTTEXT("A ROTR B : "); OUTINT(BITROTR(A,B),0); OUTIMAGE; ! ROTATE RIGHT ;
END BITWISE;
BITWISE(14,3);
END;
END
|
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #PicoLisp | PicoLisp | (de recursiveSearch (Val Lst Len)
(unless (=0 Len)
(let (N (inc (/ Len 2)) L (nth Lst N))
(cond
((= Val (car L)) Val)
((> Val (car L))
(recursiveSearch Val (cdr L) (- Len N)) )
(T (recursiveSearch Val Lst (dec N))) ) ) ) ) |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #MAD | MAD | NORMAL MODE IS INTEGER
INTERNAL FUNCTION(NUM)
ENTRY TO BINARY.
BTEMP = NUM
BRSLT = 0
BDIGIT = 1
BIT WHENEVER BTEMP.NE.0
BRSLT = BRSLT + BDIGIT * (BTEMP-BTEMP/2*2)
BTEMP = BTEMP/2
BDIGIT = BDIGIT * 10
TRANSFER TO BIT
END OF CONDITIONAL
FUNCTION RETURN BRSLT
END OF FUNCTION
THROUGH SHOW, FOR VALUES OF N = 5, 50, 9000
SHOW PRINT FORMAT FMT, N, BINARY.(N)
VECTOR VALUES FMT = $I4,2H: ,I16*$
END OF PROGRAM |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #Slate | Slate | [ |:a :b |
inform: (a bitAnd: b) printString.
inform: (a bitOr: b) printString.
inform: (a bitXor: b) printString.
inform: (a bitNot) printString.
inform: (a << b) printString.
inform: (a >> b) printString.
] applyTo: {8. 12}. |
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #PL.2FI | PL/I | /* 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 <= r);
mid = (l+r)/2;
if A(mid) = M then return (mid);
if A(mid) < M then
L = mid+1;
else
R = mid-1;
end;
return (lbound(A,1)-1);
end search; |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #Maple | Maple |
> convert( 50, 'binary' );
110010
> convert( 9000, 'binary' );
10001100101000
|
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | StringJoin @@ ToString /@ IntegerDigits[50, 2] |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #Smalltalk | Smalltalk | | testBitFunc |
testBitFunc := [ :a :b |
('%1 and %2 is %3' % { a. b. (a bitAnd: b) }) displayNl.
('%1 or %2 is %3' % { a. b. (a bitOr: b) }) displayNl.
('%1 xor %2 is %3' % { a. b. (a bitXor: b) }) displayNl.
('not %1 is %2' % { a. (a bitInvert) }) displayNl.
('%1 left shift %2 is %3' % { a. b. (a bitShift: b) }) displayNl.
('%1 right shift %2 is %3' % { a. b. (a bitShift: (b negated)) }) displayNl.
].
testBitFunc value: 16r7F value: 4 . |
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #Pop11 | Pop11 | 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) => |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #MATLAB_.2F_Octave | MATLAB / Octave | dec2bin(5)
dec2bin(50)
dec2bin(9000) |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #Standard_ML | Standard ML | fun bitwise_ints (a, b) = (
print ("a and b: " ^ IntInf.toString (IntInf.andb (IntInf.fromInt a, IntInf.fromInt b)) ^ "\n");
print ("a or b: " ^ IntInf.toString (IntInf.orb (IntInf.fromInt a, IntInf.fromInt b)) ^ "\n");
print ("a xor b: " ^ IntInf.toString (IntInf.xorb (IntInf.fromInt a, IntInf.fromInt b)) ^ "\n");
print ("not a: " ^ IntInf.toString (IntInf.notb (IntInf.fromInt a )) ^ "\n");
print ("a lsl b: " ^ IntInf.toString (IntInf.<< (IntInf.fromInt a, Word.fromInt b )) ^ "\n"); (* left shift *)
print ("a asr b: " ^ IntInf.toString (IntInf.~>> (IntInf.fromInt a, Word.fromInt b )) ^ "\n") (* arithmetic right shift *)
) |
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #PowerShell | PowerShell |
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
}
}
|
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #Maxima | Maxima | digits([arg]) := block(
[n: first(arg), b: if length(arg) > 1 then second(arg) else 10, v: [ ], q],
do (
[n, q]: divide(n, b),
v: cons(q, v),
if n=0 then return(v)))$
binary(n) := simplode(digits(n, 2))$
binary(9000);
/*
10001100101000
*/ |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #Stata | Stata | func bitwise(a: Int, b: Int) {
// All bitwise operations (including shifts)
// require both operands to be the same type
println("a AND b: \(a & b)")
println("a OR b: \(a | b)")
println("a XOR b: \(a ^ b)")
println("NOT a: \(~a)")
println("a << b: \(a << b)") // left shift
// for right shifts, if the operands are unsigned, Swift performs
// a logical shift; if signed, an arithmetic shift.
println("a >> b: \(a >> b)") // arithmetic right shift
println("a lsr b: \(Int(bitPattern: UInt(bitPattern: a) >> UInt(bitPattern: b)))") // logical right shift
}
bitwise(-15,3) |
http://rosettacode.org/wiki/Binary_search | Binary search | 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 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. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1):
change high = N-1 to high = N
change high = mid-1 to high = mid
(for recursive algorithm) change if (high < low) to if (high <= low)
(for iterative algorithm) change while (low <= high) to while (low < high)
Traditional algorithm
The algorithms are as follows (from 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:
mid = (low + high) / 2
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 low + high 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:
mid = low + (high - low) / 2
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:
mid = (low + high) >>> 1
where >>> 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
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
| #Prolog | Prolog | bin_search(Elt,List,Result):-
length(List,N), bin_search_inner(Elt,List,1,N,Result).
bin_search_inner(Elt,List,J,J,J):-
nth(J,List,Elt).
bin_search_inner(Elt,List,Begin,End,Mid):-
Begin < End,
Mid is (Begin+End) div 2,
nth(Mid,List,Elt).
bin_search_inner(Elt,List,Begin,End,Result):-
Begin < End,
Mid is (Begin+End) div 2,
nth(Mid,List,MidElt),
MidElt < Elt,
NewBegin is Mid+1,
bin_search_inner(Elt,List,NewBegin,End,Result).
bin_search_inner(Elt,List,Begin,End,Result):-
Begin < End,
Mid is (Begin+End) div 2,
nth(Mid,List,MidElt),
MidElt > Elt,
NewEnd is Mid-1,
bin_search_inner(Elt,List,Begin,NewEnd,Result). |
http://rosettacode.org/wiki/Binary_digits | Binary digits | Task
Create and display the sequence of binary digits for a given non-negative integer.
The decimal value 5 should produce an output of 101
The decimal value 50 should produce an output of 110010
The decimal value 9000 should produce an output of 10001100101000
The results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.
The output produced should consist just of the binary digits of each number followed by a newline.
There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
| #MAXScript | MAXScript |
-- MAXScript: Output decimal numbers from 0 to 16 as Binary : N.H. 2019
for k = 0 to 16 do
(
temp = ""
binString = ""
b = k
-- While loop wont execute for zero so force string to zero
if b == 0 then temp = "0"
while b > 0 do
(
rem = b
b = b / 2
If ((mod rem 2) as Integer) == 0 then temp = temp + "0"
else temp = temp + "1"
)
-- Reverse the binary string
for r = temp.count to 1 by -1 do
(
binString = binString + temp[r]
)
print binString
)
|
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
| #Swift | Swift | func bitwise(a: Int, b: Int) {
// All bitwise operations (including shifts)
// require both operands to be the same type
println("a AND b: \(a & b)")
println("a OR b: \(a | b)")
println("a XOR b: \(a ^ b)")
println("NOT a: \(~a)")
println("a << b: \(a << b)") // left shift
// for right shifts, if the operands are unsigned, Swift performs
// a logical shift; if signed, an arithmetic shift.
println("a >> b: \(a >> b)") // arithmetic right shift
println("a lsr b: \(Int(bitPattern: UInt(bitPattern: a) >> UInt(bitPattern: b)))") // logical right shift
}
bitwise(-15,3) |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.