Compare commits
1 Commits
Author | SHA1 | Date |
---|---|---|
Alexander Zhirov | 29b3bc8553 |
|
@ -0,0 +1,15 @@
|
|||
.dub
|
||||
docs.json
|
||||
__dummy.html
|
||||
docs/
|
||||
/example_5
|
||||
example_5.so
|
||||
example_5.dylib
|
||||
example_5.dll
|
||||
example_5.a
|
||||
example_5.lib
|
||||
example_5-test-*
|
||||
*.exe
|
||||
*.o
|
||||
*.obj
|
||||
*.lst
|
|
@ -0,0 +1,9 @@
|
|||
{
|
||||
"authors": [
|
||||
"alexander"
|
||||
],
|
||||
"description": "Массивы и ассоциативные массивы. Бинарный поиск.",
|
||||
"license": "proprietary",
|
||||
"name": "example_5",
|
||||
"targetPath": "bin"
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
import std.array, std.stdio;
|
||||
|
||||
bool binarySearch(T)(T[] input, T value)
|
||||
{
|
||||
while (!input.empty)
|
||||
{
|
||||
auto i = input.length / 2;
|
||||
auto mid = input[i];
|
||||
if (mid > value) input = input[0..i];
|
||||
else if (mid < value) input = input[i+1..$];
|
||||
else return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool binarySearchRecursive(T)(T[] input, T value)
|
||||
{
|
||||
if (input.empty) return false;
|
||||
auto i = input.length / 2;
|
||||
auto mid = input[i];
|
||||
if (mid > value) return binarySearchRecursive(input[0..i], value);
|
||||
if (mid < value) return binarySearchRecursive(input[i+1..$], value);
|
||||
return true;
|
||||
}
|
||||
|
||||
unittest
|
||||
{
|
||||
assert(binarySearch([1, 5, 6, 9], 6));
|
||||
assert(!binarySearch([1, 5, 6, 9], 3));
|
||||
assert(binarySearch([5.3, 6.1, 6.2, 9.4], 6.2));
|
||||
assert(!binarySearch([5.3, 6.1, 6.2, 9.4], 6.3));
|
||||
|
||||
assert(binarySearchRecursive([1, 5, 6, 9], 6));
|
||||
assert(!binarySearchRecursive([1, 5, 6, 9], 3));
|
||||
assert(binarySearchRecursive([5.3, 6.1, 6.2, 9.4], 6.2));
|
||||
assert(!binarySearchRecursive([5.3, 6.1, 6.2, 9.4], 6.3));
|
||||
}
|
||||
|
||||
void main()
|
||||
{
|
||||
|
||||
}
|
Reference in New Issue