Big O Notation Exercise
Question 1:
Find maximum element from an array of integers. What is the time complexity of your algorithm?
Analayzing the code:
The function
findMax
takes an arrayarr
and its sizen
as input.It initializes a variable
max
to the first element of the array.It then iterates through the array to find the maximum element.
The time complexity of this algorithm is , where is the size of the input array.
Question 2:
Sum of all elements in an array of integers. What is the time complexity of your algorithm?
Analayzing the code:
The function
sumArray
takes an arrayarr
and its sizen
as input.It initializes a variable
sum
to zero.It then iterates through the array to calculate the sum of all elements.
The time complexity of this algorithm is , where is the size of the input array.
Question 3:
Check if an array of integers is sorted in ascending order. What is the time complexity of your algorithm?
Analayzing the code:
The function
isSorted
takes an arrayarr
and its sizen
as input.It iterates through the array to check if each element is greater than the next element.
If it finds a pair of elements that are out of order, it returns
false
.else, it returns
true
.
The time complexity of this algorithm is , where is the size of the input array.
Question 4:
Search for a given element in an array of integers using binary search. What is the time complexity of your algorithm?
Analayzing the code:
The function
binarySearch
takes an arrayarr
, its sizen
, and a key to search for as input.It initializes two variables
low
andhigh
to the start and end of the array, respectively.It then performs a binary search to find the key in the array.
The time complexity of this algorithm is , where is the size of the input array.
Last updated