Lab04
Lab04
KT&KĐCL/11/BM02E
FACULTY OF INFORMATION TECHNOLOGY
Issue time: 01
ACADEMIC YEAR: 20..... - 20......
CODE: 503040
I. Idea
1. Divide the problem into parts.
2. Solve each part recursively.
3. Combine the Solutions.
n
4. Complexity is usually of form T (n)=aT ( b )+ f (n)
5. Recurrence relation can be solved with Master Theorem.
mergesort(A,k+1,j)
merge(A, i, k, j)
def merge(A,i,k,j):
B = [0 for _ in range(len(A))]
p1, p2, p3 = i, k+1, i
while p1 <= k and p2 <= j:
if A[p1] < A[p2]:
B[p3] = A[p1]
p1 += 1
else:
B[p3] = A[p2]
p2 += 1
p3 += 1
while p1 <= k:
B[p3] = A[p1]
p3 += 1
p1 += 1
while p2 <= j:
B[p3] = A[p2]
p3 += 1
p2 += 1
for r in range(i, j+1):
A[r] = B[r]
x = list(range(400))
shuffle(x)
print(x)
start = timeit.default_timer()
mergesort(x,0, len(x) - 1)
stop = timeit.default_timer()
print(x)
print('Time: ', stop - start)
II. Exercises
For each of the problems in this section, implement (in Python) and analyze
a divide-and-conquer algorithm to solve the problem.
Warm-up exercise
1. Find an element in an ascending sorted array.
Intermediate exercises
2. Sort an array with Quicksort
3. Identify the height of a binary tree. Suppose that the height of a tree
containing a single node is 0.