Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

USING MATLAB- write an MATLAB function named linear_search(). Your MATLAB functi

ID: 3770063 • Letter: U

Question

USING MATLAB- write an MATLAB function named linear_search(). Your MATLAB function linear_search() should have two parameters: an unsorted array of non-negative integers, and an integer target vaue (in that order). Your function should return the index where the target value is first located in the array. (The target value may occur more than once in the unsorted array.) No input testing is required. Ulike the python code which returns None if the value is not in the array, your MATLAB function should return the value 0 if the value is not found. (Note that 0 is not a valid array index in MATLAB)

Explanation / Answer

function index = linear_search(array,key)
index = 0
for i = 1:numel(array)
if key == array(i)
index = i
break %because we have to find only position of first occurence of key hence we break out of the loop
end
end
end

array = [4,2,3,4,5]
key = 4
result = linear_search(array,key)
if result==0
fprintf("Element %d not found in the array ",key);
else
fprintf("Element %d found at index %d in the array ",key,result);
end