IN1002 Computation and Reasoning Practice Sheet: Complexity

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

IN1002 Computation and Reasoning

Practice sheet: complexity

This worksheet provides practice with big-O (asymptotic) complexity.


Consider the following computations on an array of length n. In each case, give the time
complexity for the whole computation in big-O notation in its simplest form.

1. Return the length of the array.

2. Call an O(n2 ) method 20 times.

3. Call an O(n2 ) method n times.

4. Call an O(log n) method n times.

5. Return the middle element of the array.

6. Call an O(2n ) method 32 times.

7. Call an O(log n) method and then an O(n2 ) method.

8. Call an O(n5 ) method and then an O(2n ) method.

9. Call an O(n3 ) method and then another O(n3 ) method.

10. Perform a merge sort followed by a binary search.

11. Perform a merge sort followed by an insertion sort.

12. Perform a merge sort followed by a selection sort.

13. Add 1 to each element of the array.

14. This algorithm to multiply together all the elements of the array:

Product(a[0..n-1])
i0
prod 1
WHILE i < n
prod prod * a[i]
i i+1
RETURN prod

15. This algorithm to find the position of the largest element in the array:

1
MaxPos(a[0..n1])
max 0
i1
WHILE i < n
IF a[i] > a[max]
max i
ii+1
RETURN max

16. This algorithm to count the number of duplicates in the array:

CountDups(a[0..n1])
count 0
i0
WHILE i < n1
j i+1
WHILE j < n
IF a[i] = a[j]
count = count + 1
RETURN count

17. This alternative algorithm to count the number of duplicates in the array:

CountDups2(a[0..n1])
sort the array using merge sort
count 0
i0
WHILE i < n1
IF a[i] = a[i+1]
count = count + 1
RETURN count

You might also like