Jump to content

[PASCAL] Binary Search


CouldnoT
 Share

Recommended Posts

Binary Search

 

A binary search first compares the search item to an item at the middle of the list. If there is not a match, the code determines which half of the list to carry out the next search using the same method. This iterative or recursive process is repeated until the search item is found or it is shown to be absent.

 

bePceUMnSG-binary_search_gif.gif

 

This is a demonstration for the binary search :

 

program BinarySearchDemo;
const
  UPPER_BOUND = 16;
  Nums : array[1 .. UPPER_BOUND] of integer =  (61, 87, 154, 170, 275,
           426, 503, 509, 512, 612, 653, 677, 703, 765, 897, 908);
var
  Num : integer;

procedure BinarySearch(SearchNum : integer);
var
  Found, Failed: Boolean;
  Last, First, MidPoint: integer;
begin
  Found := False;
  Failed:= False;
  Last := UPPER_BOUND;
  First := 1;
  repeat
    Midpoint := (First + Last) DIV 2;
    if Nums[MidPoint] = SearchNum then
      begin
        Found := True;
        writeln('Found at position ' ,MidPoint);
      end
    else if (First > Last) then
      Failed := true;
    else if Nums[MidPoint] < SearchNum then
      First := MidPoint + 1;
    else
      Last := MidPoint - 1;
  until Found or Failed;
  if Failed then
    writeln('Not found.');
end;

begin
  writeln('Enter the number to search for: ');
  readln(Num);
  BinarySearch(Num);
  readln;
end.

 

 

Edited by CouldnoT
Link to comment
Share on other sites

Guest
This topic is now closed to further replies.
 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.