LAB1
LAB1
LAB1
TUTORIAL
1. Using the Big Oh Notation, indicate the time requirement of each of the following tasks in the
worst case. Describe any assumption that you make.
a. After arriving at a party, you shake hands with each person there.
b. Each person in a room shakes hands with everyone else in the room.
c. You climb a flight of stairs.
d. You slide down the banister.
e. After entering an elevator, you press a button to choose a floor.
f. You ride the elevator from the ground floor up to the nth floor.
g. Display all the integers in an array of integers in reverse order.
h. Display all the integers in a chain of linked nodes in reverse order.
i. Display the nth integers in an array of integers from end.
j. Compute the sum of the first n even integers in a chain of linked nodes.
2. For each of the following codes, find the Big Oh for the following pseudocode algorithm
a) int CompareSmallestNumber (int array[ ])
{
int x, curMin;
/* iterate through each element in array, assuming there are only 10 elements*/
{
if(string.equal(“Hello”)
{return true;}
return false;
System.out.println(”Jimmy One”);
System.out.println(”Jimmy Two”);
}
e. char key;
........
switch(key) {
case 'a':
sum += X[i];
break;
case 'b':
sum += Y[i][j];
break;
PROGRAMMING TASK
1. Three algorithms for computing the sum 1 + 2 + .. + n for an integer n>0 are as follow:
Algorithm A Algorithm B Algorithm C
sum = 0 sum= 0 sum = n * (n + 1) /2
for i=1 to n for i=1 to n
sum=sum+ i {
for j=1 to i
sum = sum + 1
}
a. Translate these algorithms into Java codes and calculate the time taken to run for
each algorithms when n = 1000, n= 100,000 and n = 1,000,000.
b. What can you conclude for these 3 algorithms?
//Loop B
for (i=1; i<=n;i++)
for(j=1; j<=n;j++)
sum= sum+j;
Although Loop A is O(n) and Loop B is O(n2), Loop B can be faster than Loop A for small values
of n. Design and implement an experiment to find a value of n for which Loop B is faster.