Compare commits

...
This repository has been archived on 2021-11-27. You can view files and clone it, but cannot push or open issues or pull requests.

1 Commits

Author SHA1 Message Date
Alexander Zhirov 29b3bc8553 example 5 2021-11-09 19:08:49 +03:00
3 changed files with 67 additions and 0 deletions

15
src/example_5/.gitignore vendored Normal file
View File

@ -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

9
src/example_5/dub.json Normal file
View File

@ -0,0 +1,9 @@
{
"authors": [
"alexander"
],
"description": "Массивы и ассоциативные массивы. Бинарный поиск.",
"license": "proprietary",
"name": "example_5",
"targetPath": "bin"
}

View File

@ -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()
{
}