Reputation: 11
Suppose we have an array w
, that contains n
integers. By the following definition, and the following pseudo code, please, tell me what is the time complexity of the algorithm w.r.t. n
:
idx[i] = max(j) : 1 <= j < i and w[j] < w[i]
alg:
Data: w : array of integers - idx: a pointer to maximum index with the less value.
Date: w is 1based
idx[1] = -1
for i=: 2 to n do
j=i-1
while w[j] > w[i] and j <> -1
{
j = idx[j]
}
idx[i] =j
end
Upvotes: 0
Views: 490
Reputation: 73608
You have 2 loops here -
for loop
runs n times. hence its O(n).while loop
runs each time from (i-1) + (i-2) + (i-3) + .... + (i-n)
. it runs for (n-1) times. So O(n).Combines to O(n^2)
algo. The other operations are either constant time or O(n) time, hence neglected.
Upvotes: 1