Logo

Programming-Idioms

History of Idiom 124 > diff from v32 to v33

Edit summary for version 33 by Jere:
[Pascal] You have to return at the end of the function, for better readability. Also, use better "( )" to separate arithmetics.

Version 32

2020-10-15, 17:33:58

Version 33

2021-05-03, 14:54:05

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.

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.

Variables
binarySearch,x,a
Variables
binarySearch,x,a
Extra Keywords
dichotomic dichotomy
Extra Keywords
dichotomic dichotomy
Code
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;
Code
function BinarySearch(X: Integer; A: Array of Integer): Integer;
var
  L, R, I, Cur, answer: Integer;
  isIt :boolean;
begin
  isIt := false;
  answer := -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 begin
	answer := cur;
	isIt : = true;
    end;
    if (X > Cur) then
       L := I + 1
    else
      R := I - 1
  end;
  BinarySearch := answer;
end;