function analyzeLinearSearch()
% Analyze the time complexity of linear search, i.e.,
% how long does it take to search a vector whose length is 2, 4, 8, ...

nLens= 20; % No. of vector lengths to consider
nTrials= 100; % No. of searches for each vector length
aveTime= zeros(1,nLens); % aveTime(k) is the average search time given a
% vector of length 2^k

% Call function linearSearch once to load it Matlab memory
f= linearSearch(3, rand(1,10));

% Do nTrials linear search trials for each of the nLens vector lengths
disp('Vector length Average search time (1e-6 sec)')
vecLengths= zeros(1,nLens);
for k= 1:nLens
% The kth vector length to consider
vecLengths(k)= 2^k; % Length of vector in which to perform a search
trialTimes= zeros(1,nTrials);
for trial= 1:nTrials
% Generate random data for one trial of linear search
[vec, target]= genData(0, 2^(2*k), vecLengths(k));
% Time the search
tic;
f= linearSearch(target, vec);
trialTimes(trial)= toc;
end
aveTime(k)= mean(trialTimes);
fprintf(' 2^%2d %10.2f\n', k, aveTime(k)*1e6)
end

% Plot average search time vs vector length
plot(vecLengths, aveTime, 'k*')
xlabel('Vector Length', 'FontSize',16, 'FontWeight','bold')
ylabel('Mean Search Time (sec)', 'FontSize',16, 'FontWeight','bold')

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [v, t] = genData(lo, hi, n)
% v is a vector of length n where each element is an interger that is
% uniformly random in [lo..hi].
% t is a scalar integer that is uniformly random in [lo..hi]
v= floor(rand(1,n+1)*(hi-lo+1)) + lo;
t= v(n+1);
v= v(1:n);