Ad

Linear search with while loop:

  • Instead of
    • Every Iteration
  1. check if i is smaller than length of array, if not increament i
  2. check if arr[i] equals to x
  • Do
    • Once
  1. check if last item is equal to x, if yes return index
  2. if not, replace last array item with x, saving the last item in another variable
  3. if i is smaller than length of array, return i
  4. else return nil
    - Every Iteration
  5. 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