Data Structure Time Complexity Questions
Data Structure Time Complexity Questions
1. Sum =0; }
for ( i=0; i<n; i++) return count;
Sum += i; 8. for (int count = 0, i = 0; i < N; i++){
2. Sum =0; for (int j = i; j < N; j++){
for ( i=0; i<n; i++) if(j % 2 == 0) break;
for ( j=0; j<n; j++) count++;
Sum += j; }
3. Sum =0; }
for ( i=0; i<n; i++) 9. for (long count = 0, i = N; i > 0; i--){
for ( j=0; j<n*n; j++) long j = i;
Sum += j; while (j >0){
4. Sum =0; count+=j;
for ( i=0; i<n; i++) j/= 2;}
for ( j=0; j<i; j++) }
Sum += j; 10. for (int count = 0, i = 1; i < =N; i*=2){
5. Sum =0;
for (int j = 1; j <= i; j++){
for ( i=0; i<n; i++)
for ( j=0; j<i; j++) count++;
for ( k=0; k<j; k+
}
+)
Sum += k; }
6. Sum =0; 11. long factorial (int x) {
for ( i=0; i<n; i++) if (x > 0)
Sum += i; return x * factorial(x - 1);
for ( j=0; j<n*n; j++) else
compute_val(sum,j); return 1;
(The run time complexity of the }
function compute_val(x,y) is given to 12. int mystery(int x) {
be n + nlog2n) if (x > 0)
7. count=0; return mystery(x-1) +
while(x>0){ 2*x - 1;
y=x%10; else
If(y%2==0) count++; return 0;
x=x/10 }
1
HiLCoE
School of Computer Science and Technology
Data Structure and Algorithm Analysis (CS321)
ii. Without writing an algorithm, tell the Big-Oh representation of the following problems.
Whenever there is an array assume the size of the array is big enough.
long ASum(int d, int n){ long Gsum(int n, int b){ double Pow( ldouble x, int
long sum =0; long sum =1, exps; n ){
for ( long i=1; i<=n; i++) for ( int i=1; i<=n; i++){ long p=1;
sum += i; exps=1; if(x==0)
return sum; for(j=1; j<=i; j++) return 0;
} exps=exps*b; else{
sum=sum + exps;} for(int i=1; i<=n; i+)
return sum;} p=p*x;
}
return p;}
3
vi. Algorithm ‘A’ does a certain task in a ‘time’ n + 200n + 1000 where n is the number of
elements processed. Algorithm ‘B’ does the same task in a ‘time’ of 30n 2 + 1000.
a) What are the Big-O requirements of each of the algorithms?
b) Which algorithm is more efficient by Big-O standards?
c) Under what conditions, if any, would the less efficient algorithm execute more
quickly than the more efficient algorithm?
vii. The input is an N-by-N matrix of numbers that is already in memory. Each individual row
is increasing from left to right. Each individual column is increasing from top to bottom.
Give an O(N) worst-case algorithm that decides if a number X is in the matrix.
2