






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







Welcome to CS 125, a course on algorithms and computational complexity. First, what do these terms means? An algorithm is a recipe or a well-defined procedure for performing a calculation, or in general, for transform- ing some input into a desired output.
In this course we will ask a number of basic questions about algorithms:
Meanwhile, computational complexity theory focuses on classification of problems according to the com- putational resources they require (time, memory, randomness, parallelism, etc.) in various computational models. Computational complexity theory asks questions such as
Some algorithms very familiar to us all are those those for adding and multiplying integers. We all know the grade school algorithm for addition from kindergarten: write the two numbers on top of each other, then add digits right
1-
Figure 1.1: Grade school multiplication.
to left while keeping track of carries. If the two numbers being added each have n digits, the total number of steps (for some reasonable definition of a “step”) is n. Thus, addition of two n-digit numbers can be performed in n steps. Can we take fewer steps? Well, no, because the answer itself can be n digits long and thus simply writing it down, no matter what method you used to obtain it, would take n steps.
How about integer multiplication? Here we will describe several different algorithms to multiply two n-digit integers x and y.
Algorithm 1. We can multiply x · y using repeated addition. That is, add x to itself y times. Note all intermediate sums throughout this algorithm are between x and x · y, and thus these intermediate sums can be represented between n and 2n digits. Thus one step of adding x to our running sum takes at most 2n steps. Thus the total number of steps is at most 2n · y. If we want an answer purely in terms of n, then an n-digit number y cannot be bigger than 10 n^ − 1 (having n 9’s). Thus 2n · y ≤ 2 n · ( 10 n^ − 1 ) ≈ 2 n · 10 n. In fact usually in this course we will ignore leading constant factors and lower order terms (more on that in section!), so this bound is at most roughly n · 10 n, or as we will frequently say from now on, O(n · 10 n). This bound is quite terrible; it means multiplying 10-digit numbers already takes about 100 billion steps!
Algorithm 2. A second algorithm for integer multiplication is the one we learned in grade school, shown in Figure 1.1. That is, we run through the digits of y, right to left, and multiply them by x. We then sum up the results after multiplying them by the appropriate powers of 10 to get the final result. What’s the running time? Multiplying one digit of y by the n-digit number x takes n steps. We have to do this for each of the n digits of y, thus totaling n^2 steps. Then we have to add up these n results at the end, taking n^2 steps. Thus the total number of steps is O(n^2 ). As depicted in Figure 1.1 we also use O(n^2 ) memory to store the intermediate results before adding them. Note that we can reduce the memory to O(n) without affecting the running time by adding in the intermediate results to a running
Thus, unfortunately we’ve done nothing more than give yet another O(n^2 ) algorithm more complicated than Algorithm 2.
Algorithm 4. Algorithm 3, although it didn’t give us an improvement, can be modified to give an improvement. The following algorithm is called Karatsuba’s algorithm and was discovered by the Russian mathematician Anatolii Alexeevitch Karatsuba in 1960. The basic idea is the same as Algorithm 3, but with one clever trick. The key thing to notice here is that four multiplications is too many. Can we somehow reduce it to three? It may not look like it is possible, but it is using a simple trick. The trick is that we do not need to compute ad and bc separately; we only need their sum ad + bc. Now note that (a + b)(c + d) = (ad + bc) + (ac + bd). So if we calculate ac, bd, and (a + b)(c + d), we can compute ad + bc by the subtracting the first two terms from the third! Of course, we have to do a bit more addition, but since the bottleneck to speeding up this multiplication algorithm is the number of smaller multiplications required, that does not matter. The recurrence for T (n) is now T (n) = 3 T (n/ 2 ) +Cn. Then, drawing the recursion tree again, there are only 3k^ nodes at level k instead of 4k, and each one requires doing Cn/ 2 k^ work. Thus the total work of the algorithm is, again for h = log 2 n,
Cn + 32 Cn +
Cn +... +
)h Cn = Cn ·
2
)h+ (^1) − 1 (^32) − 1 , where we used the general fact that 1 + p + p^2 +... + pm^ = (pm+^1 − 1 )/(p − 1 ) for p 6 = 1. Now, using the general fact that we can change bases of logarithms, i.e. loga m = logb m/ logb a, we can see that ( 3 / 2 )log^2 n^ = ( 3 / 2 )log^3 /^2 n/^ log^3 /^2 2 = n^1 /^ log^3 /^2 2. Then changing bases again, log 3 / 2 2 = log 2 2 / log 2 ( 3 / 2 ) = 1 /(log 2 3 − 1 ). Putting ev- erything together, our final running time is then O(nlog^2 3 ), which is O(n^1.^585 ), much better than the grade school algo- rithm! Now of course you can ask: is this the end? Is O(nlog^2 3 ) the most efficient number of steps for multiplication? In fact, it is not. The Sch¨onhage-Strassen algorithm, discovered in 1971, takes a much smaller O(n log 2 n log 2 log 2 n) steps. The best known algorithm to date, discovered in 2007 by Martin F¨urer, takes O(n log 2 n 2 C^ log∗^ n) for some constant C ≤ 8. Here, log∗^ n is the number of base-2 logarithms one must take of n to get down to a result which is at most 1. The point is, it is a very slow growing function. If one took log∗^ of the number of particles in the universe, the result would be at most 5! Also, Karatsuba’s algorithm is not just a source of fun for theorists, but actually is used in practice! For example, it is used for the implementation of integer multiplication in Python. If you want to check it out for yourself, here’s what I did on my GNU/Linux machine:
wget https://www.python.org/ftp/python/3.5.2/Python-3.5.2.tar.xz tar xvfJ Python-3.5.2.tar.xz emacs Python-3.5.2/Objects/longobject.c
Now look through that file for mentions of Karatsuba! Most of the action happens in the function k mul.
Now that we’ve seen just how cool algorithms can get. With the invention of computers in this century, the field of algorithms has seen explosive growth. There are a number of major successes in this field:
In designing an algorithm, it is often easier and more productive to think of a computer in abstract terms. Of course, we must carefully choose at what level of abstraction to think. For example, we could think of computer operations in terms of a high level computer language such as C or Java, or in terms of an assembly language. We could dip further down, and think of the computer at the level AND and NOT gates.
For most algorithm design we undertake in this course, it is generally convenient to work at a fairly high level. We will usually abstract away even the details of the high level programming language, and write our algorithms in ”pseudo-code”, without worrying about implementation details. (Unless, of course, we are dealing with a pro- gramming assignment!) Sometimes we have to be careful that we do not abstract away essential features of the problem.
operation can be done in unit time.
Example:
7 5 9 3 1 7 5 9 3 1 5 7 9 3 1 5 7 9 3 1 5 7 3 9 1 5 7 3 1 9 5 7 3 1 9 5 7 3 1 9 5 3 7 1 9 5 3 1 7 9 5 3 1 7 9 3 5 1 7 9 3 1 5 7 9 3 1 5 7 9 1 3 5 7 9
1.2.1.2 MergeSort
So we can sort in O(n^2 ) operations. Can we do better? Yes. There are a number of algorithms that can sort in just O(n log n) operations. (Note that asymptotically n log 2 n is much much smaller than n^2 ; the ratio n log 2 n/n^2 goes to 0.) One of simplest is mergesort:
function mergesort (s) list s, s 1 , s 2 if size(s) = 1 then return(s) split(s, s 1 , s 2 ) s 1 = mergesort(s 1 ) s 2 = mergesort(s 2 ) return(merge(s 1 , s 2 )) end mergesort
Break the list into two equal-sized (or as equal as possible) sublists, sort each sublist recursively, and merge the two sorted lists (by going through them together in order). A merge function is given below (using basic list operators push and pop).
function merge (s,t) list s,t if s = [ ] then return t else if t = [ ] then return s else if s( 1 ) ≤ t( 1 ) then u:= pop(s) else u:= pop(t) return push(u, merge(s,t)) end merge
Let T (n) be the number of comparisons mergesort performs on lists of length n. Then T (n) satisfies the recurrence relation T (n) ≤ 2 T (n/ 2 ) + n − 1. (If n is odd, then really T (n) ≤ T (⌈n/ 2 ⌉) + T (⌊n/ 2 ⌋) + n − 1; not a significant difference.) This follows from the fact that to sort lists of length n we sort two sublists of length n/2 and then merge them using (at most) n − 1 comparisons. Using the general theory on solutions of recurrence relations, we find that T (n) = O(n log n). Exercise: Prove directly that the recurrence T (n) ≤ 2 T (n/ 2 ) + n with T ( 2 ) = 1 yields T (n) ≤ n log 2 n for n a power of 2 by expanding the recurrence directly.
1.2.1.3 Lower Bounds
So far we’ve been considering what we can do – how fast we can sort. Now we want to think about something more challenging – are there limits to how fast we can sort? This is more challenging because when we ask how fast, we just need to consider and analyze one algorithm. When we ask about limits, we seek a lower bound for all possible algorithms, or at least all possible algorithms in a certain class of algorithms. Trying to prove a statement about all possible algorithms can be, as you might imagine, difficult. Let us try to frame the problem in order to obtain a lower bound. The BubbleSort algorithm and the MergeSort algorithm are both based on comparing elements to put them in the right place. How many comparisons are needed to sort n elements correctly every time? Formally, let us consider algorithms that start with an array A = (ai) and only do two kinds of operations; they compare elements (“is ai > a (^) j”), and they move elements. Our goal will be to prove the following theorem:
Theorem 1.1 Any deterministic comparison-based sorting algorithm must perform Ω(n log n) comparisons to sort n elements in the worst case. More specifically, for any such algorithm, there exists some input with n elements that requires at least log 2 (n!) comparisons.
the Wikipedia page for more details – here we’ll assume the elements are distinct.) If our input is a 1 , a 2 ,... , an, we keep track of counts; for each ai, we increase its count:
count[ai]+ = 1.
Now we walk through the count array, updating it via what is called a prefix sum operation, so that the count[ j] contains the number of inputs that are less than or equal to j. Finally, we walk back through the inputs; for each ai, it’s sorted position is now count[ai ]. The two passes through the input take O(n) operations; the pass through the count array to compute the prefix sum takes O(k) operations. Here we are making assumptions about the input, and expanding our model of computation. Instead of just comparisons, we’re accessing a non-trivially sized array. In particular, we are assuming that we can maninpulate values with ⌈log 2 k⌉ bits in one unit of time, and use these values to do things like access arrays. If k for example is n, this means we are assuming we can work with number of size log 2 n bits.
As the discussion above suggests, in order to precisely specify an algorithm, we need to precisely specify a model of computation — what kind of operations are allowed, and on what kind of data? Having a precise model is particularly important if we want to be able to understand the limitations of algorithms — what is impossible for algorithms to achieve. An example is the above proof that any comparison-based algorithm for sorting requires Ω(n log n) comparisons. But the fact that we can beat this lower bound by working in a more general, but still very reasonable, model of computation, suggests that the choice of model might be very important. Can there be a robust theory of computing, that is not sensitive to arbitrary details of our model of computation? Remarkably, the answer turns out to be yes. In a few weeks, we will see that there is a simple model of computation, known as the Turing machine, that can compute the same functions as any reasonable model of computation. It was formulated in the 1930’s by Alan Turing, motivated by questions in the foundations of mathematics (related to Godel’s Incompleteness Theorem). It inspired the development of actual physical computers, and its relevance has not diminished despite all the changes in computing technology. Using the Turing machine model, we will prove that there are some well-defined computational problems that cannot be solved by any algorithm whatsoever. For example:
For bucket sort, we again make assumptions about the input – this time, we assume the inputs are randomly selected according to some distribution. Because of this “randomness” in the input, we consider the “expected time” to sort instead of worst case time. Here we assume that the n input numbers are uniform over a collection of numbers in the range ( 0 , M], and show that the expected time to sort is O(n). (More general results are possible.) We put the numbers into n buckets of size M/n, with the numbers 1 to M/n going in the first bucket, the next M/n numbers going in the second bucket, and so on. We then sort by using BubbleSort on each bucket, and then concatenating the results from each bucket in order. If Xi is the number of elements that land in the ith bucket, the expected number of comparison operations to sort T is given by:
E T ≤ E
n
n
= n E X 12.
Now, let us define indicator random variables Y 1 ,... ,Yn where Yj is 1 if item j landed in bucket 1, else Yj = 0. Then X 1 = (^) ∑nj= 1 Yj, so
E X 12 = E
( (^) n
n
= n · (^1) n + n(n − 1 ) · (^) n^12 < 2
Sorting remains an active area for research; the best sorting algorithm might still not be known, in part because the right model for machine operations is open to interpretation. One often hears of an Ω(n log n) lower bound for sorting. That lower bound is correct in the most general setting for data where all one can do with two elements is compare them, but taking advantage of even simple aspects of the data, such as that they are numbers within some fixed range (e.g. counting sort), can lead to sorting algorithms that break the lower bound.