Algorithms and complexity · A level · OCR H446 2.3.1, AQA 7517 4.4.4.1, Eduqas A500QS 1.3 · about 25 min
Dominant terms, the orders of complexity from O(1) to O(2^n), deriving complexity from code, best, average and worst case, and space complexity.
[1 mark]An algorithm makes 4n² + 30n + 500 operations. What is its time complexity?
[1 mark]Put these orders of complexity from slowest-growing to fastest-growing.
Number the lines 1 to 6 to put them in the right order.
O(log n)O(n log n)O(n²)O(n)O(2ⁿ)O(1)[1 mark]A loop runs n times, and inside it a second loop also runs n times. What is the time complexity?
[1 mark]A loop halves a variable that starts at n until it reaches 1. What is its time complexity?
[1 mark]How many times does the marked line run? The program prints the count.
count = 0
n = 1000
while n > 1:
n = n // 2
count = count + 1 # the marked line
print(count)[1 mark]When a single Big O is quoted for an algorithm without saying which case, which case does it normally describe?
Each function in the starter has one line marked # the step. Change each function so that, instead of its answer, it returns the number of times its step ran. Then, for n = 8, 16 and 32, call each function on list(range(n)) (a list of n different numbers; halvings takes the number n itself) and print one line per function in exactly this form, with the three counts and then the order of growth:
- first: <count for 8> <count for 16> <count for 32> O(1)
- total: ... O(n)
- has_duplicate: ... O(n^2)
- halvings: ... O(log n)
Count the step in first as running once. Do not type the counts in: the program must work them out.
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
def first(items):
return items[0] # the step
def total(items):
s = 0
for x in items:
s = s + x # the step
return s
def has_duplicate(items):
for i in range(len(items)):
for j in range(i + 1, len(items)):
if items[i] == items[j]: # the step
return True
return False
def halvings(n):
count = 0
while n > 1:
n = n // 2 # the step
count = count + 1
return countPlan your program here, then type it in and press Run.