Previous topic | Next topic | Ada Home Page | Index

Binary search

Binary search involves picking the midpoint of a range in an array, and determining which side of the midpoint a desired value should lie in.

This happens in a loop, which stops when the desired value is found or the range becomes zero and the value is known not to be present.

Each time the loop is executed, the mid point is found between first and last. Then the same process is performed on a smaller range in the array.

Make this recursive:

	function binary_search (first,last,tofind: in integer; 
                                a: in int_array) return integer is
	    mid:integer;		
		
	begin
	    if (first>last) then return -1;
	    end if;
	    mid := (first+last)/2
   	    if a(mid)=tofind then return mid;
	    end if;
	    if a(mid)<tofind then 
	       return binary_search(mid+1,last,tofind,a);
	    end if;
	    return binary_search(first,mid-1,tofind,a);
        end binary_search;


Previous topic | Next topic | Ada Home Page | Index
c-lokan@adfa.oz.au / 23 Feb 96