Algorithmic Thinking
Algorithmic Thinking
1: Motivation
Imagine a list of 100 million sorted numbers (e.g. [1, 3, 55, 100, 125, ...]). One day you want to
check if a number X, say 17717, exists in the list. How would you do it?
1.1) Linear Search - Dumb way (and the most the straightforward)
You can scan the list from start to end. One by one.
If you find X, then you are done.
Otherwise, we reach the end of the list without finding X, which the list does not contain
X.
This is the first question we always ask when we come up with an approach:
Q1) How long will it take: in the worst case? best case? on average?
For the sake of discussion, let's say it takes 1 second to scan a number.
If X is somewhere near the end of the list, then we need roughly 100 million seconds.
This is the worst case.
If X is somewhere near the beginning of the list, then we need much much less than 100
million seconds (maybe just a few hundred seconds). This is the best case.
On average, we can intuitively say that we need 50 million seconds to find X.
Illustration:
https://docs.google.com/presentation/d/1p-agsx6MxPD14XnSbjfcSDYBajRun_AGrhvg2E-oOik/
edit?usp=sharing
Q2 Can we do better?
In this case, given the scenario, binary search is already one of the faster algorithms we can
use for finding item in a sorted list. Binary search is said to take O(log N) (i.e. logarithmic time),
while linear search is said to take O(N) (i.e. linear time). We will understand exactly what those
means over the course of study.
As you can see, different algorithms can result in a drastically different performance
characteristics for the same task!
2: Pseudocode
To discuss algorithm more succinctly without having to be bogged down by the details of a
programming language, we can make use of "pseudocode". A pseudocode is just a way of
writing procedures that resembles programming languages without strict rules on syntax. The
main idea is to help communicate algorithms and data structures with each other. Different
programmer might have different styles, and that is fine.
Let's start with the linear search algorithm. We can write it this way in pseudocode:
let A be a l
ist of integers
v al is a n integer
As you can see, writing in C could potentially obscure the main idea behind the algorithm itself.
let A be a l
ist of sorted integers
v al is a n integer
The pseudocode style can change over the course, but as long as we can understand exactly
what is going on, it is fine.
3: Exercise
Let's kickstart by implementing the above two algorithms.
You can use Visual C++ to implement the algorithms, and use the pseudocode above as
guidance.
Binary search has a powerful and simple concept, but is notoriously difficult to get right.
You can experiment and see how far you can implement it.
Over the course of study, we will develop a way of thinking that can help you reason about and
debug your implementation effectively.