This is NOT homework, but practice problems from class. There is no solution key to it I know. I would like to see if I did it right. Also, how would I find the time complexity? Below are my solutions at the bottom of this.
Determine the Big Oh complexity of the following program fragments
1)
void sum1(int n){
sum1 = 0;
for(i=1; i<=n; i++)
for (j=1; j<=n; j++)
sum1++;
}
2)
void sum2(int n){
sum2 = 0;
for(i=1; i<=n; i++)
for (j=1; j<=i; j++)
sum2++;
}
3)
float useless(a){
n = a.length;
if (n==1){
return a[0];
}
// let a1, a2 be arrays of size n/2
for (i=0; i <= (n/2)-1; i++){
a1[i] = a[i];
a2[i] = a[n/2 +i];
}
for (i=0; i<=(n/2)-1; i++){
for (j = i+1; j<=(n/2) -1; j++){
if(a1[i] == a2[j])
a2[j] = 0;
}
}
b1 = useless(a1);
b2 = useless(a2);
return max(b1,b2);
}
4)
void sum3(int n) {
sum = 0;
for(i=0; i<sqrt(n)/2; i++)
sum++;
for(j=0; j<sqrt(n)/4; j++)
sum++;
for(k=0; k<8+j; k++)
sum++;
}
5)
void sum4(int n){
sum = 0;
for(i=0; i<sqrt(n)/2; i++)
for(j=1; j<8+i; j++)
for(k=j; k<8+j; k++)
sum++;
}
below is my solutions, the '?' means I'm not sure what to put in
1)
void sum1(int n){
sum1 = 0; --> 1
for(i=1; i<=n; i++) --> n
for (j=1; j<=n; j++) --> n^(2)
sum1++; --> ?
}
Answer: O(n^(2))
2)
void sum2(int n){
sum2 = 0; --> 1
for(i=1; i<=n; i++) --> n
for (j=1; j<=i; j++) --> n^(2)
sum2++; --> ?
}
Answer: O(n^(2))
3)
float useless(a){
n = a.length; --> ?
if (n==1){
return a[0]; --> ?
}
// let a1, a2 be arrays of size n/2
for (i=0; i <= (n/2)-1; i++){ --> n
a1[i] = a[i]; --> ?
a2[i] = a[n/2 +i]; --> ?
}
for (i=0; i<=(n/2)-1; i++){ ---> n+n = n
for (j = i+1; j<=(n/2) -1; j++){ ---> n^(2)
if(a1[i] == a2[j])
a2[j] = 0; --> 1
}
}
b1 = useless(a1); --> ?
b2 = useless(a2); --> ?
return max(b1,b2); --> ?
}
I am very stuck on this one...
4)
void sum3(int n) {
sum = 0; --> 1
for(i=0; i<sqrt(n)/2; i++) --> n
sum++; --> ?
for(j=0; j<sqrt(n)/4; j++) --> n^(2)
sum++; --> ?
for(k=0; k<8+j; k++) --> n^(3)
sum++; --> ?
}
Answer: O(n^(3))
5)
void sum4(int n){
sum = 0; --> 1
for(i=0; i<sqrt(n)/2; i++) --> n
for(j=1; j<8+i; j++) --> n^(2)
for(k=j; k<8+j; k++) --> n^(3)
sum++; --> ?
}
Answer: O(n^(3))