For simplicity, consider size of the list to be a power of 3.
if j-i+1 <= 3:
# Compute their minimum
return min(i:j+1)
The if
statement forms the base case. Time complexity of above statements is O(1)
. However, the if statement will be executed n
times.
T(n)
|
______________________|______________________
| | |
| | |
T(n/3) T(n/3) T(n/3)
| | |
_______|_______ _______|_______ _______|_______
| | | | | | | | |
| | | | | | | | |
T(n/9) T(n/9) T(n/9) T(n/9) T(n/9) T(n/9) T(n/9) T(n/9) T(n/9)
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
T(1) T(1) T(1) T(1) T(1) T(1) T(1) T(1) T(1) --- (n/3) * T(1)
It should be obvious from the recursion tree, that for an array of size n
, if
statement will be executed n/3
times. Hence, overall complexity of if
statement is O(n)
.
The reason if
is executed n/3
times and not n
is that recursion ends when we encountered an sub-array of size 3 . If the the recursion came to an end when we encountered an sub-array of size 1, then it would have been executed for n times.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.