Reputation: 39
A college instructor here. I am trying to find a meaningful (practical) code example to illustrate different time complexities for beginners in a ELi5 manner. The code should start with constant complexity and then incrementally, by adding small piece of code, increases in complexity: .., logn, n, nlogn, n^2, 2^n, ..
I think I can explain it better with one example that has small incremental changes rather than switch the context from searching to sorting to brute force algorithms .
Upvotes: 2
Views: 61
Reputation: 46487
Any example will be artificial. But here is one that does reasonably well.
Let vec
be a sorted array of numbers, i
an integer, and x
be another number. In order answer the following questions.
O(1)
What is the value of vec[i]
?O(n)
Is x
in a range from vec
by linear search?O(log(n))
Is x
in a range from vec
by binary search?O(n^2)
Is x
the sum of two elements in a range from of vec
by a double loop?O(n log(n))
Is x
the sum of two elements of vec
by linear search on the first with a binary search on the second. (Simplifying trick, do a linear search on the smaller and binary on the second. then reuse your code from 3.)O(2^n)
Is x
the sum of any subset of elements of vec
by recursion?Upvotes: 2