Here is my code for binary search:
function result = binarySearch(a, key)
binaryFound = false;
halfIndex = fix(length(a)/2) + 1;
if a(halfIndex) == key
binaryFound = true;
elseif length(a)==1 && a(1)~=key
binaryFound = false;
elseif key > a(halfIndex)
newHalfArray = a(halfIndex+1:end);
binaryFound = binarySearch(newHalfArray, key);
else
newHalfArray = a(1:halfIndex-1);
binaryFound = binarySearch(newHalfArray, key);
end
result = binaryFound;
And here is my linear search:
function linearFound = linearSearch(a, key)
linearFound = false;
for j=1:length(a)
if a(j) == key
linearFound = true;
end
end
In both cases, 'a' is an array of sorted integers and 'key' is the value I'm looking for. Having run multiple tests with a range of array sizes and averaging of runtimes, I consistently find my linear search to be faster than my binary search. I know from theory that the binary search is supposed to be faster. What am I doing wrong?