function x = bisect(f, int, tol)
% bisect - bisection algorithm for the scalar equation f(x) = 0
% 
%   Syntax: 
%           x = bisect(f, int, tol)
%   Arguments: 
%           f - function handle pointing to a function file  
%           int - 1x2 matrix specifying an interval int = [a,b]
%           tol - a tolerance 
%   Returns: 
%           x - an approximate solution in the interval int = [a,b]
%   Description:
%           The program bisect uses the bisection algorithm to 
%           compute an approximate solution of the scalar equation
%           f(x) = 0 in the interval int = [a,b].  The function file must 
%           contain the function y = f(x).  The function values f(a) 
%           and f(b) must have opposite signs.  Then the program
%           computes an approximate solution x with the error
%           |x-x_exact| < tol.  It returns an empty value for x if
%           f(a) and f(b) have the same sign.  
%   Examples: 
%          x = bisect(@sin,[1,4],1e-7)   computes pi to 7 decimals
%
%----------------------------------------------------------------------

a=int(1);                  % left interval endpoint 
b=int(2);                  % right endpoint

% add code here to interchange a and b in case a>b.
if a>b
    bb=b; 
    b=a;
    a=bb;
end

% add code here that displays an appropriate message, and then stops
% and returns x = [] if fa and fb do not have opposite signs

if f(a)*f(b)>=0
    disp('Bisection fails: f(a) and f(b) have the same sign.')
    x=[];
    return
end

% add code here that displays an appropriate message and stops if the
% given tolerance is not positive.

if ~(tol>0)
    disp('Bisection fails: the tolerance is not positive.')
    x=[];
    return
end
    
% replace the ?'s to get a working bisection solver
% test the solver on problems with known solution to ensure it works
 
while b-a>tol

  x=(a+b)/2;             % compute midpoint x of (current) interval [a b]
  fx=f(x);               % evaluate f at midpoint

  if fx==0                   % root
      break                  % jump out of while loop
  elseif f(a)*fx<0           % root in the left half 
    b=x;                     % move b
  else 
    a=x;                    
  end

end

x=(a+b)/2;
