Algorithm Assignment 1
Algorithm Assignment 1
Assignment 1 – 16%
Start: Week 3
Due Date: Week 7
Method Order
(big-Oh)
a) public void add(int i, Object e){ e
Node newNode = new Node(e, null);
if(size==0){ O(i)
head=newNode;
tail = newNode;
return;
}
int k=0;
Node node = this.head;
while(k<i){
node=node.next;
k++;
}
if(k==0){ //Add element e to the beginning of the list
newNode.next=head;
head = newNode;
} if( k == zise){ //Add element e to the end of the list
node.next = newNode;
tail = newNode;
}else {
newNode.next=node.next;
node.next=newNode;
}
size++;
return;
}
1
Node node2 = node1.next;
node1.next=null;
while(node2!=null){
Node node3 = node2.next;
node2.next=node1;
node1=node2;
node2=node3;
}
head = node1;
}
2
2. Based on the following algorithm:
int total1 = 0;
int total2 = 0;
for (int x = 0; x <= n; x++)
total1 = total1 + x;
for (int y = 1; y < n; y++)
total2 += total1 * y;
Show the steps to find the total operations of the algorithm given by fill in the table given.
Then, define the value of Big Oh in its worse-case. (5 mark)
Assignment 2
Addition n+n-1
Multiplication n-1
Total Operation 3n
O(n)
The big Oh is = ________________ (1mark)
3
3. Suppose that a class, Employee, is defined as follows:
class Employee {
String lastName;
String firstName;
double hourlyWage;
int yearsWithCompany;
}
Write a code segment that will output the first name, last name, and hourly wage of each
employee who has been with the company for 20 years or more.
4. What tree results when you add the values 44, 88, 55, 77, 33, 99, 66, 22, 25 and 75 to each of the
following initially empty trees?
a) Binary Search Tree (1mark)
ii) delete node ‘44’ (after deleting node 55) and redraw the tree.
(1mark)
c) AVL tree (1 mark)
a) b) i) b) ii)
c) d)
/ \
/ \ / | \
4
5. Based on this following binary tree :
Pahang
Johor Kedah
Kelanta Sabah
5.
6.
a) b) i) - M * / + P Q * * S T U
b) ii) M P Q + S / T U * * -