Our Lecturer gave us his code
procedure linear_search (x: integer; a1, a2, …, an: integers)
i := 1
while ( i ≤ n and x ≠ ai )
i := i + 1
if i ≤ n then
location := i
else
location := 0
and this is mine
method Search (x integer, a1,a2....an integers)
for i from 1 to n
start
if ai = x, location = i, break.
else i++, location = 0.
stop
In terms of steps, my code takes 2n + 1
steps to finish while the other code takes 2n + 2
, therefore my code is logically faster. However, in Big O terms, they're both O(n)
.
So what do I say, which one is faster? Or do I say they're equal?