Linear search with while loop:
- Instead of
- Every Iteration
- check if i is smaller than length of array, if not increament i
- check if arr[i] equals to x
- Do
- Once
- check if last item is equal to x, if yes return index
- if not, replace last array item with x, saving the last item in another variable
- if i is smaller than length of array, return i
- else return nil
- Every Iteration - check if arr[i] equals to x, if not increament i
def Linear_search(arr,x)
i=0
last_idx=arr.size-1
if arr[last_idx] == x
return last_idx
else
last = arr[last_idx]
arr[last_idx]=x
end
while arr[i]!=x
i+=1
end
i < last_idx ? i : nil
end
describe "Linear Search" do
it "Test for search result" do
Test.assert_equals(Linear_search([1,4,5,3,7,10], 7), 4)
Test.assert_equals(Linear_search([1,4,5,7,3,10], 7), 3)
Test.assert_equals(Linear_search([1,4,5,10,3,7], 7), 5)
Test.assert_equals(Linear_search([1,4,5,10,3,6], 7), nil)
end
end