Реализации алгоритмов/Двоичный поиск: различия между версиями

Заменён пример на Python; добавлен пример на C#
(+C, C++, Java из Википедии)
(Заменён пример на Python; добавлен пример на C#)
{{wikipedia|Двоичный поиск}}
 
== [[w:Си (язык программирования)|C]] ==
<source lang="c">
#include <stdio.h>
</source>
 
== [[w:C++|C++]] ==
<source lang="cpp">
#include <iostream>
</source>
 
== [[w:JavaC_Sharp|JavaC#]] ==
<source lang="csharp">
static int BinarySearch <T> (T[] array, int value, bool descending = false) where T : IComparable
{
int left = 0;
for (int right = array.Length, middle; left < right; )
{
middle = left + (right - left) / 2;
var c = array[middle].CompareTo(value);
if (c == 0)
return middle;
if ((c < 0) == descending)
right = middle;
else
left = middle + 1;
}
return ~left;
}
</source>
 
==[[w:Java|Java]]==
<source lang="java">
package binarysearch;
</source>
 
== [[w:PL/SQL|PL/SQL]] ==
 
<source lang="plsql">
 
<source lang="python">
def binary_search (sorted_list, value, descending=False):
def binsearch(array, k, low, high):
left = 0
for _ in range(int(math.log2(high - low)) + 1):
midright = low + len(high - lowsorted_list) // 2
while left < if k == array[mid]right:
middle = left + return(right mid- left) // 2
if midsorted_list[middle] == low == highvalue:
return -1middle
if k(sorted_list[middle] < array[mid]value) == descending:
highright = mid - 1middle
else:
lowleft = midmiddle + 1
return ~left
</source>
 
74

правки