Professional Documents
Culture Documents
IN1002 Computation and Reasoning Practice Sheet: Complexity
IN1002 Computation and Reasoning Practice Sheet: Complexity
IN1002 Computation and Reasoning Practice Sheet: Complexity
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
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