Homework Lecture3 Complexity
Homework Lecture3 Complexity
Homework week 3
Complexity analyses
1. Sort the following functions in the ascending order of Big O notation:
n2 + 10n(n^2) n3 ~nlogn
210
3n + 100 logn
4n
2logn
nlogn
4nlogn+2n
n2 + 10n
2n
n3
2. Given an integer number n, your task is to write two different algorithms in
pseudo-codes to calculate 2n, and evaluate the complexity of the algorithms.
a,function power_of_two_1(n):
result = 1
for i from 1 to n:
result = result * 2
return result
b,function power_of_two_2(n):
if n == 0:
return 1
else:
return 2 * power_of_two_2(n - 1)
a, một vòng for chạy n lần nên O là n
b,đệ quy với độ sâu là n -> 0
3. Your task is to write operations of queue data structure in pseudo-codes using an
array, then evaluate the complexities of the operations.
queue impletation:
Khởi tạo queue :
tạo mảng array dể chứa queue
O(n)
Enqueue:
kiểm tra array
thêm phẩn tử vào cuối array
O(1)
Dequeue
kiểm tra array
xóa phần tử ở đàu
O(1)
function enqueue(data)
node = new Node(data)
if queue is empty
front = node
rear = node
else
rear.next = node
rear = node
O(1)
function dequeue()
if queue is not empty
temp = front
front = front.next
delete temp
else
print "Queue is empty"
O(1)
function push(data)
if stack is not full
top = top + 1
stack[top] = data
else
print "Stack is full"
O(1)
function pop()
if stack is not empty
data = stack[top]
top = top - 1
return data
else
print "Stack is empty"
O(1)