This language bar is your friend. Select your favorite languages!

Idiom #124 Binary search for a value in sorted array

Write function binarySearch which returns the index of an element having value x in sorted array a, or -1 if no such element.

a.binary_search(&x).unwrap_or(-1);
import std.range;
import std.algorithm;
long binarySearch(long[] a, long x) {
    long result = a.assumeSorted.lowerBound(x).length;
    if (result == a.length || a[result] != x)
        return -1;
    return result;
}
def binarySearch(ar, el)
  res = ar.bsearch{|x| x == el}
  res ? res : -1
end
func binarySearch(a []T, x T) int {
	imin, imax := 0, len(a)-1
	for imin <= imax {
		imid := (imin + imax) / 2
		switch {
		case a[imid] == x:
			return imid
		case a[imid] < x:
			imin = imid + 1
		default:
			imax = imid - 1
		}
	}
	return -1
}
import "sort"
func binarySearch(a []int, x int) int {
	i := sort.SearchInts(a, x)
	if i < len(a) && a[i] == x {
		return i
	}
	return -1
}
import "sort"
func binarySearch(a []T, x T) int {
	f := func(i int) bool { return a[i] >= x }
	i := sort.Search(len(a), f)
	if i < len(a) && a[i] == x {
		return i
	}
	return -1
}
binSearch :: Ord a => a -> [a] -> Maybe Int
binSearch _ [] = Nothing
binSearch t l = let n = div (length l) 2
                    (a, m:b) = splitAt n l in
                if t < m then binSearch t a
                else if t > m then aux (binSearch t b)
                else Just n where
    aux :: Maybe Int -> Maybe Int
    aux (Just x) = Just (x+n+1)
    aux _ = Nothing
function BinarySearch(X: Integer; A: Array of Integer): Integer;
var
  L, R, I, Cur: Integer;
begin
  Result := -1;
  if Length(A) = 0 then Exit;
  L := Low(A);
  R := High(A);
  while (L <= R) do
  begin
    I := L + (R - L) div 2;
    Cur := A[I];
    if (X = Cur) then Exit(I);
    if (X > Cur) then
       L := I + 1
    else
      R := I - 1;
  end;
end;
import bisect
def binarySearch(a, x):
    i = bisect.bisect_left(a, x)
    return i if i != len(a) and a[i] == x else -1
def binary_search(ar, el)
  ar.bsearch_index{|x| x == el} || -1
end

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

programming-idioms.org