This tutorial gives you more exercises on big Oh-nations.

advertisement

CS2468 Tutorial (Week 3)

This tutorial gives you more exercises on big Oh-nations. Give a big-Oh characterization for question 1 and question 2. 1.

Algorithm

MatrixMultiplication(matrix A, matrix B)

Input Output

two matrices: matrix A ( matrix C (

m

*

p

) = AB

m

*

n

for

i

 0

to

m

-1

do for

j

 0

to

p

-1

do

C

i

,

j

 0

for

k

 0

to

n

-1

do

C

i

,

j

 C

i

,

j

+ A

i

,

k

* B

k

,

j

return

C ) and matrix B (

n

*

p

) 2.

Algorithm

binarySearch (int

sortedArray[ ]

, int

n

, int

key

)

Input

a sorted array

sortedArray

in increasing order (supposed that no two elements are equal to each other), the length of the array

n

, and an element to be searched for

key

Output

position of the element

key

or -1 if the element is not in the array low  0 high 

n

– 1

while

low ≤ high mid  (low + high) / 2 if sortedArray [mid] =

key

return

mid

if

sortedArray

[mid] <

key

low  mid + 1

else

high  mid – 1

return

-1

3.

Given the Node class as

public class Node { // Instance variables: private Object element; private Node next; /** Creates a node with null references to its element and next node. */ public Node() { this(null, null); } /** Creates a node with the given element and next node. */ public Node(Object e, Node n) { element = e; next = n; } // Accessor methods: public Object getElement() { return element; } public Node getNext() { return next; } // Modifier methods: public void setElement(Object newElem) { element = newElem; } public void setNext(Node newNext) { next = newNext; } }

How can you use it to implement the Stack and Queue interfaces? What is the time cost for each stack and queue operations?

Extra Exercise:

1)

f(n) = 2 * f(n/2) 1

if if

n≥2 n=1

What is the value of f(n) in terms of n?

2)

f(n) = 3 * f(n/3) 1

if

n≥2

if

n=1

What is the value of f(n) in terms of n?

3)

f(n) = f(n/3) 1

if

n≥2

if

n=1

What is the value of f(n) in terms of n?

Download