CouldnoT Posted August 17, 2020 Share Posted August 17, 2020 (edited) 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. 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 August 17, 2020 by CouldnoT 1 Link to comment Share on other sites More sharing options...
CouldnoT Posted August 20, 2020 Author Share Posted August 20, 2020 (edited) Edited October 21, 2020 by CouldnoT Link to comment Share on other sites More sharing options...
Recommended Posts