In comments you state that it takes O(1) to update the waiting time of a process, so that means the following line takes O(N):
Compute waiting time for all process in array
Concerning the remove
operation you also suggest that it is O(1), although you should not set the corresponding waiting time to zero, as that would impact other actions on the array (like sorting and getting the median). Better is to copy the last process into slot i, and then drop the last element from the array. That would be O(1).
The execution of the for
loop then takes O(N). Finding the median in a sorted array is also O(N), so in the do
body the operation with the greatest time complexity is the sorting: O(N⋅logN)
In each iteration of the do
loop, the array size (N) is halved.
So we have the following equation (leaving out the big-O notation):
T(N) = N⋅log(N) + T(N/2)
= N⋅log(N) + (N/2)⋅log(N/2) + (N/4)⋅log(N/4) + ...
= N⋅(log(N) + (1/2)⋅log(N/2) + (1/4)⋅log(N/4) + ...)
Now log(N/c) = log(N) - log(c), so we can group terms like follows:
= N⋅((1 + 1/2 + 1/4 + ...)⋅log(N) - log(2)/2 - log(4)/4 - log(8)/8 - ...)
= N⋅(2⋅log(N) - log(2)/2 - log(4)/4 - log(8)/8 - ...)
< 2N⋅log(N)
So we started out that T(N) is at least O(N⋅log(N)), and we derive that it is at most O(N⋅log(N)), so we have a tight bound for the time complexity:
O(N⋅log(N))