Big O notation gives us an estimate of the number of operations we have to perform in order to use the algorithm on N elements if Big O notation is n then we need to n operations to perform for the function.
Linear search in list takes Big O of n
Why
def linearsearch(numbers,s):
for i in range(len(numbers)):
if numbers[i] == s:
return i
return -1
We will look a worst case that s is not in the list. For that, we will do all constant operations n times if our list size is n.
When n increase time will be increase linearly since the time taken for the linearsearch depends on size of the list
If all constant operations take c time then when we do for 5 elements it takes 5c and if we do for 10 elements it takes 10c (Here we assume the worst case when there is no s in the list)
Lets see O(n2)
If we have n elements then the time taken will be square of n
Lets look following linear search in 2D list
Numbers = [[1,2,3][4,5,6]]
def linearsearch(numbers,s):
for inner in range(len(numbers)):
for i in range(len(numbers[inner])):
if numbers[inner][i] == s:
return i
return -1
With above code and we consider some assumptions to illustrate n2
Inner list has n elements and outer list also has n innerlist
When we need to search an element like s inside the innerlist then we need to do the thoee operations n2 times
If we have 2 elements in the innerlist and 2 innerlist in the outer list
Then 4 c will be average time if we consider c for time taken for constant operations 3,3 then 9
So if we have n elements inside the inner list then the tims complexity will be O(n2)