algorithm - How to determine the worst case run time of each program using big-O notation? -


this question has answer here:

i having trouble understanding question , how answer. how calculate worst case run time?

the input of following programs array containing n integers a[ 1 ] · · · a[n]. bound worst case run time of each program using big-o notation.

problem 1:

i = 1, total = 0  while < n/2:     total = total + a[i]      i=i*2 

problem 2:

total = 0 s = set {1,2,3,4...n}  each subset t of s     each element x in t           total = total + a[x] 

problem 3:

int = 1, j = 1;      = 1 n:           while (j < n && a[i] < a[j])              j++ 

the prefix sum of array of numbers a[ 1 ], . . . , a[n] second array b[ 1 ], . . . , b[n] where

b[i] = summation j=1 i a[j]

the following problems calculate prefix sum:

problem 4:

for = 1 n:      b[i] = 0;     j = 1 i:           b[i] += a[j] 

problem 5:

b[1] = a[1];  = 2 n:       b[i] = b[i-1] + a[i] 

problem 1:
algorithm performs constant time operation (addition) @ point of each access, , access made while i<n/2. since i doubles each time, condition no longer hold after log(n/4) steps , worst case time complexity o(log(n)) (logarithmic).

problem 2:
algorithm accesses each element of array (x in pseudocode) many times in subset of s, , performs constant time operation @ point of access. every element in 2^(n-1) subsets that contain itself, , there n such elements, worst case time complexity o(n * 2^(n)) (exponential).

problem 3:
observe @ every time condition in while loop checked, value of i+j increases 1, , value of i+j can never decrease. since i+j starts @ 2 , can never go past 2n+1, overall complexity of algorithm o(n) (linear).

problem 4:
given value of i, inner loop runs i times. further, i ranges 1 n, perform 1+2+3+...+n = n(n+1)/2 constant-time computations (additions), overall complexity of algorithm o(n^2) (quadratic).

problem 5:
algorithm accesses n-1 elements of array, , performs constant time operation @ point of each access (addition), worst case time complexity o(n) (linear).


Comments

Popular posts from this blog

Sort a complex associative array in PHP -

vb.net - How to ignore if a cell is empty nothing -

recursion - Can every recursive algorithm be improved with dynamic programming? -