Docsity

Data Structures and Analysis Lecture Notes, Lecture notes of Data Structures and Algorithms

Partial preview of the text

Download Data Structures and Analysis Lecture Notes and more Lecture notes Data Structures and Algorithms in PDF only on Docsity!

David Liu

Data Structures and Analy-

sis

Lecture Notes for CSC 263 (Version 0. 2 )

Department of Computer Science

University of Toronto

Contents

  • 1 Introduction and analysing running time
    • How do we measure running time?
    • Three different symbols
    • Worst-case analysis

1 Introduction and analysing running time

Before we begin our study of different data structures and their applications, we need to discuss how we will approach this study. In general, we will follow a standard approach:

  1. Motivate a new abstract data type or data structure with some examples and reflection of previous knowledge.

  2. Introduce a data structure, discussing both its mechanisms for how it stores data and how it implements operations on this data.

  3. Justify why the operations are correct.

  4. Analyse the running time performance of these operations.

Given that we all have experience with primitive data structures such as arrays (or Python lists), one might wonder why we need to study data structures at all: can’t we just do everything with arrays and pointers, already available in many languages?

Indeed, it is true that any data we want to store and any operation we want to perform can be done in a programming language using primitive constructs such as these. The reason we study data structures at all, spending time in- venting and refining more complex ones, is largely because of the performance improvements we can hope to gain over their more primitive counterparts.

This is not to say arrays and pointers play no role. To the contrary, the study of data structures can be viewed as the study of how to organize and synthesize basic programming language components in new and sophisticated ways.

Given the importance of this performance analysis, it is worth reviewing what you already know about how to analyse the running time of algorithms, and pointing out some common misconceptions and subtleties you may have missed along the way.

How do we measure running time?

As we all know, the amount of time a program or single operation takes to run depends on a host of external factors — computing hardware, other running processes — over which the programmer has no control.

So, in our analysis, we focus on just one central measure of performance: the re- lationship between an algorithm’s input size and the number of basic operations the algorithm performs. But because even what is meant by “basic operation” can

8 david liu

differ from machine to machine or programming language to programming lan- guage, we do not try to precisely quantify the exact number of such operations, but instead categorize how the number grows relative to the size of the algorithm’s input.

This is our motivation for Big-Oh notation, which is used to bring to the fore- ground the type of long-term growth of a function, hiding all the numeric con- stants and smaller terms that do not affect this growth. For example, the func- tions n + 1, 3n − 10, and 0.001n + log n all have the same growth behaviour as n gets large: they all grow roughly linearly with n. Even though these “lines” all have different slopes, we ignore these constants and simply say that these functions are O(n), “Big-Oh of n.” (^) We will not give the formal definition of Big-Oh here. For that, please consult We call this type of analysis asymptotic analysis, since it deals with the long-term the CSC 165 course notes. behaviour of a function. It is important to remember two important facts about asymptotic analysis:

  • The target of the analysis is always a relationship between the size of the input and number of basic operations performed. What we mean by “size of the input” depends on the context, and we’ll always be very careful when defining input size throughout this course. What we mean by “basic operation” is any operation whose running time does not depend on the size of the algorithm’s input. (^) This is deliberately a very liberal definition of “basic operation.” We don’t want you to get hung up on step counting, because that’s completely hidden by Big-Oh expressions.
  • The result of the analysis is a qualitative rate of growth, not an exact number or even an exact function. We will not say “by our asymptotic analysis, we find that this algorithm runs in 5 steps” or even “...in 10n + 3 steps.” Rather, expect to read (and write) statements like “we find that this algorithm runs in O(n) time.”

Three different symbols

In practice, programmers (and even theoreticians) tend to use the Big-Oh sym- bol O liberally, even when the precise definition of O is not exactly what we intended. However, in this course it will be important to be precise, and we will actually use three symbols to convey different pieces of information, so you will be expected to know which one means what. Here is a recap:

  • Big-Oh. f = O(g) means that the function f (x) grows slower or at the same rate as g(x). So we can write x^2 + x = O(x^2 ), but it is also correct to write (^) Or, “g is an upper bound on the rate of x^2 + x = O(x^100 ) or even x^2 + x = O( 2 x^ ). growth of f .”
  • Omega. f = Ω(g) means that the function f (x) grows faster or at the same rate as g(x). So we can write x^2 + x = Ω(x^2 ), but it is also correct to write (^) Or, “g is a lower bound on the rate of x^2 + x = Ω(x) or even x^2 + x = Ω(log log x). growth of f .”
  • Theta. f = Θ(g) means that the function f (x) grows at the same rate as g(x). (^) Or, “g has the same rate of growth as So we can write x^2 + x = Θ(x^2 ), but not x^2 + x = Θ( 2 x^ ) or x^2 + x = Θ(x). f .” Note: saying f = Θ(g) is equivalent to saying that f = O(g) and f = Ω(g), i.e., Theta is really an AND of Big-Oh and Omega.

10 david liu

size n?” we instead aim to answer the question “what is the maximum possible running time of this algorithm for an input size n?” The first question’s answer might be a whole range of values; the second question’s answer can only be a single number, and that’s how we get a function involving n.

Some notation: we typically use the name T(n) to represent the maximum pos- sible running time as a function of n, the input size. The result of our analysis could be something like T(n) = Θ(n), meaning that the worst-case running time of our algorithm grows linearly with the input size.

Bounding the worst case

But we still haven’t answered the question: where do O and Ω come in? The answer is basically the same as before: even with our restricted focus on worst- case running time, it is not always possible to calculate an exact expression for this function. What is usually easy to do, however, is calculate an upper bound on the maximum number of operations. One such example is the likely familiar line of reasoning, “the loop will run at most n times” when searching for 263 in a list of length n. Such analysis, which gives a pessimistic outlook on the most number of operations that could theoretically happen, results in an exact count — e.g., n + 1 — which is an upper bound on the maximum number of operations. From this analysis, we can conclude that T(n), the worst-case running time, is O(n).

What we can’t conclude is that T(n) = Ω(n). There is a subtle implication here of the English phrase “at most.” When we say “you can have at most 10 chocolates,” it is generally understood that you can indeed have exactly 10 chocolates; whatever number is associated with “at most” is achievable.

In our analysis, however, we have no way of knowing that the upper bound we obtain by being pessimistic in our operation counting is actually achievable. This is made more obvious if we explicitly mention the fact that we’re studying the maximum possible number of operations: “the maximum running time is less than or equal to n + 1” surely says something different than “the maximum running time is equal to n + 1.”

So how do we show that whatever upper bound we get on the maximum is actually achievable? In practice, we rarely try to show that the exact upper bound is achievable, since that doesn’t actually matter. Instead, we try to show that an asymptotic lower bound — an Omega — is achievable. For example, we might want to show that the maximum running time is Ω(n), i.e., grows at least as quickly as n.

To show that the maximum running time grows at least as quickly as some func- tion f , we need to find a family of inputs, one for each input size n, whose run- ning time has a lower bound of f (n). For example, for our problem of searching for 263 in a list, we could say that the family of inputs is “lists that contain only 0 ’s.” Running the search algorithm on such a list of length n certainly requires checking each element, and so the algorithm takes at least n basic operations. From this we can conclude that the maximum possible running time is Ω(n). (^) Remember, the constants don’t matter. The family of inputs that contain only 1 ’s for the first half, and only 263 ’s for the second half, would also have given

data structures and analysis 11

To summarize: to perform a complete worst-case analysis and get a tight, Theta bound on the worst-case running time, we need to do the following two things:

(i) Give a pessimistic upper bound on the number of basic operations that could occur for any input of a fixed size n. Obtain the corresponding Big-Oh expres- sion (i.e., T(n) = O( f )). (^) Observe that (i) is proving something about all possible inputs, while (ii) is proving something about just one family of inputs.

(ii) Give a family of inputs (one for each input size), and give a lower bound on the number of basic operations that occurs for this particular family of inputs. Obtain the corresponding Omega expression (i.e., T(n) = Ω( f )).

If you have performed a careful analysis in (i) and chosen a good family in (ii), then you’ll find that the Big-Oh and Omega expressions involve the same function f , and which point you can conclude that the worst-case running time is T(n) = Θ( f ).

Average-case analysis

So far in your career as computer scientists, you have been primarily concerned with worst-case algorithm analysis. However, in practice this type of analysis often ends up being misleading, with a variety of algorithms and data structures having a poor worst-case performance still performing well on the majority of possible inputs.

Some reflection makes this not too surprising: focusing on the maximum of a set of numbers (like running times) says very little about the “typical” number in that set, or, more precisely, the distribution of numbers within that set. In this section, we will learn a powerful new technique that enables us to analyse some notion of “typical” running time for an algorithm.

Warmup

Consider the following algorithm, which operates on a non-empty array of inte- gers:

1 def evens_are_bad(lst): 2 if every number in lst is even: 3 repeat lst.length times: 4 calculate and print the sum of lst 5 return 1 6 else : 7 return 0

Let n represent the length of the input list lst. Suppose that lst contains only even numbers. Then the initial check on line 2 takes Ω(n) time, while the com- putation in the if branch takes Ω(n^2 ) time. This means that the worst-case (^) We leave it as an exercise to justify why the if branch takes Ω(n^2 ) time.

data structures and analysis 13

per element, and hence 5n^ possible inputs in all. So 2n^ inputs have all even numbers and take n^2 + n steps, while the remaining 5n^ − 2 n^ inputs take n steps.

Number Steps all even 2 n^ n^2 + n the rest 5 n^ − 2 n^ n The average running time is:

Tavg(n) = 2 n(n^2 + n) + ( 5 n^ − 2 n)n 5 n^ (5n^ inputs total)

= 2

nn 2 5 n^

  • n

=

)n n^2 + n

= Θ(n) Remember that any exponential grows faster than any polynomial, so the first term goes to 0 as n goes to infinity.

This analysis tells us that the average-case running time of this algorithm is Θ(n), as our intuition originally told us. Because we computed an exact expres- sion for the average number of steps, we could convert this directly into a Theta expression.

As is the case with worst-case analysis, it won’t always be so easy to compute an exact expression for the average, and in those cases the usual upper and lower bounding must be done.

The probabilistic view

The analysis we performed in the previous section was done through the lens of counting the different kinds of inputs and then computing the average of their running times. However, there is a more powerful technique: treating the algorithm’s running time as a random variable T, defined over the set of possible inputs of size n. We can then redo the above analysis in this probabilistic context, performing these steps:

  1. Define the set of possible inputs and a probability distribution over this set. In this case, our set is all lists of length n that contain only elements in the range 1 - 5 , and the probability distribution is the uniform distribution. (^) Recall that the uniform distribution assigns equal probability to each element in the set.

  2. Define how we are measuring runtime. (This is unchanged from the previous analysis.)

  3. Define the random variable T over this probability space to represent the running time of the algorithm. (^) Recall that a random variable is a function whose domain is the set of inputs. In this case, we have the nice definition

T =

n^2 + n, input contains only even numbers n, otherwise

  1. Compute the expected value of T, using the chosen probability distribution and formula for T. Recall that the expected value of a variable is determined by taking the sum of the possible values of T, each weighted by the probability of obtaining that value.

E [T] = ∑

t

t · Pr[T = t]

14 david liu

In this case, there are only two possible values for T:

E [T] = (n^2 + n) · Pr[the list contains only even numbers]

  • n · Pr[the list contains at least one odd number]

= (n^2 + n) ·

)n

  • n ·

)n)

= n^2 ·

)n

  • n

= Θ(n)

Of course, the calculation ended up being the same, even if we approached it a little differently. The point to shifting to using probabilities is in unlocking the ability to change the probability distribution. Remember that our first step, defining the set of inputs and probability distribution, is a great responsibility of the ones performing the runtime analysis. How in the world can we choose a “reasonable” distribution? There is a tendency for us to choose distributions (^) What does it mean for a distribution to that are easy to analyse, but of course this is not necessarily a good criterion for be “reasonable,” anyway? evaluating an algorithm.

By allowing ourselves to choose not only what inputs are allowed, but also give relative probabilities of those inputs, we can use the exact same technique to analyse an algorithm under several different possible scenarios. This is both the reason we use “weighted average” rather than simply “average” in our above definition of average-case, and also how we are able to calculate it.

Exercise Break!

  1. 1 Prove that the evens_are_bad algorithm on page 11 has a worst-case running time of O(n^2 ), where n is the length of the input list.

  2. 2 Consider this alternate input space for evens_are_bad: each element in the list is even with probability 10099 , independent of all other elements. Prove that under this distribution, the average-case running time is still Θ(n).

  3. 3 Suppose we allow the “all-evens” check on line 2 of evens_are_bad to stop immediately after it finds an odd element. Perform a new average-case anal- ysis for this mildly-optimized version of the algorithm using the same input distribution as in the notes. Hint: part of the running time T now can take on any value between 1 and n; first compute the probability of getting each of these values, and then use the expected value formula.

Quicksort is fast on average

The previous example may have been a little underwhelming, since it was “ob- vious” that the worst-case was quite rare, and so not surprising that the average- case running time is asymptotically faster than the worst-case. However, this is

16 david liu

Let T be the random variable counting the number of comparisons made. Before starting the computation of E [T], we define additional random variables: for each i, j ∈ {1,... , n} with i < j, let Xij be the indicator random variable defined as:

Xij =

1, if i and j are compared 0, otherwise Because each pair is compared at most once, we obtain the total number of

Remember, this is all in the context of choosing a random permutation. comparisons simply by adding these up:

T =

n

i= 1

n

j=i+ 1

Xij.

The purpose of decomposing T into a sum of simpler random variables is that we can now apply the linearity of expectation (see margin note). (^) If X, Y, and Z are random variables and X = Y + Z, then E [X] = E [Y] + E [Z], even if Y and Z are dependent.

E [T] =

n

i= 1

n

j=i+ 1

E [Xij]

n

i= 1

n

j=i+ 1

Pr[i and j are compared] Recall that for an indicator random variable, its expected value is simply the probability that it takes on the value

To make use of this “simpler” form, we need to investigate the probability that i and j are compared when we run quicksort on a random array. Proposition 1. 1. Let 1 ≤ i < j ≤ n. The probability that i and j are compared when running quicksort on a random permutation of {1,... , n} is 2/(j − i + 1 ).

Proof. First, let us think about precisely when elements are compared with each other in quicksort. Quicksort works by selecting a pivot element, then comparing the pivot to every other item to create two partitions, and then recursing on each partition separately. So we can make the following observations:

(i) Every comparison must involve the “current” pivot.

(ii) The pivot is only compared to the items that have always been placed into the same partition as it by all previous pivots. (^) Or, once two items have been put into different partitions, they will never be So in order for i and j to be compared, one of them must be chosen as the compared. pivot while the other is in the same partition. What could cause i and j to be in different partitions? This only happens if one of the numbers between i and j (exclusive) is chosen as a pivot before i or j is chosen. So then i and j are compared by quicksort if and only if one of them is selected to be pivot first out of the set of numbers {i, i + 1,... , j}.

Because we’ve given an implementation of quicksort that always chooses the first item to be the pivot, the item that is chosen first as pivot must be the one that appears first in the random input permutation. Since we choose the permutation (^) Of course, the input list contains other numbers, but because our partition algorithm preserves relative order within a partition, if a appears before

data structures and analysis 17

uniformly at random, each item in the set {i,... , j} is equally likely to appear first, and thus be chosen first as pivot.

Finally, because there are j − i + 1 numbers in this set, the probability that either i or j is chosen first is 2/(j − i + 1 ), and this is the probability that i and j are compared. 

Now that we have this probability computed, we can return to our expected value calculation to complete our average-case analysis.

Theorem 1. 2 (Quicksort average-case runtime). The average number of com- parisons made by quicksort on a uniformly chosen random permutation of {1,... , n} is Θ(n log n).

Proof. As before, let T be the random variable representing the running time of quicksort. Our previous calculations together show that

E [T] =

n

i= 1

n

j=i+ 1

Pr[i and j are compared]

n

i= 1

n

j=i+ 1

j − i + 1

=

n

i= 1

n−i

j′^ = 1

j′^ + 1 (change of index j′^ = j − i)

n

i= 1

n−i

j′^ = 1

j′^ + 1 i^ j′^ values 1 1, 2, 3,... , n − 2, n − 1 2 1, 2, 3,... , n − 2 .. . .. . n − 3 1, 2, 3 n − 2 1, 2 n − 1 1 n

Now, note that the individual terms of the inner summation don’t depend on i; only the bound does. The first term, when j′^ = 1, occurs when 1 ≤ i ≤ n − 1, or n − 1 times in total; the second (j′^ = 2) occurs when i ≤ n − 2, and in general the j′^ = k term appears n − k times.

So we can simplify the counting to eliminate the summation over i:

E [T] = 2

n− 1

j′^ = 1

n − j′ j′^ + 1

n− 1

j′^ = 1

n + 1 j′^ + 1

= 2 (n + 1 )

n− 1

j′^ = 1

j′^ + 1 − 2 (n − 1 )

We will use the fact from mathematics that the function (^) ∑n i=− 11 i+^11 is Θ(log n), (^) Actually, we even know the exact constant hidden in the Θ: Look up the Harmonic series if you’re interested in learning more!

and so we get that E [T] = Θ(n log n). 

2 Priority Queues and Heaps

In this chapter, we will study our first major data structure: the heap. As this is our first extended analysis of a new data structure, it is important to pay attention to the four components of this study outlined at the previous chapter:

  1. Motivate a new abstract data type or data structure with some examples and reflection of previous knowledge.

  2. Introduce a data structure, discussing both its mechanisms for how it stores data and how it implements operations on this data.

  3. Justify why the operations are correct.

  4. Analyse the running time performance of these operations.

Abstract data type vs. data structure

The study of data structures involves two principal, connected pieces: a speci- fication of what data we want to store and operations we want to support, and an implementation of this data type. We tend to blur the line between these two components, but the difference between them is fundamental, and we often speak of one independently of the other. So before we jump into our first major data structure, let us remind ourselves of the difference between these two.

Definition 2. 1 (abstract data type, data structure). An abstract data type (ADT) is a theoretical model of an entity and the set of operations that can be performed on that entity. (^) The key term is abstract: an ADT is a definition that can be understood and A data structure is a value in a program which can be used to store and operate communicated without any code at all. on data.

For example, contrast the difference between the List ADT and an array data structure.

List ADT
  • Length(L): Return the number of items in L.
  • Get(L, i): Return the item stored at index i in L.
  • Store(L, i, x): Store the item x at index i in L.

20 david liu

There may be other operations you think are fundamental to lists; we’ve given as bare-bones a definition as possible.

This definition of the List ADT is clearly abstract: it specifies what the possible operations are for this data type, but says nothing at all about how the data is stored, or how the operations are performed.

It may be tempting to think of ADTs as the definition of interfaces or abstract classes in a programming language – something that specifies a collection of methods that must be implemented – but keep in mind that it is not necessary to represent an ADT in code. A written description of the ADT, such as the one we gave above, is perfectly acceptable.

On the other hand, a data structure is tied fundamentally to code. It exists as an entity in a program; when we talk about data structures, we talk about how we write the code to implement them. We are aware of not just what these data structures do, but how they do them.

When we discuss arrays, for example, we can say that they implement the List ADT; i.e., they support the operations defined in the List ADT. However, we can say much more than this:

  • Arrays store elements in consecutive locations in memory
  • They perform Get and Store in constant time with respect to the length of the array.
  • How Length is supported is itself an implementation detail specific to a particular language. In C, arrays must be wrapped in a struct to manually store their length; in Java, arrays have a special immutable attribute called length; in Python, native lists are implemented using arrays an a member to (^) At least, the standard CPython imple- store length. mentation of Python.

The main implementation-level detail that we’ll care about this in course is the running time of an operation. This is not a quantity that can be specified in the definition of an ADT, but is certainly something we can study if we know how an operation is implemented in a particular data structure.

The Priority Queue ADT

The first abstract data type we will study is the Priority Queue , which is similar in spirit to the stacks and queues that you have previously studied. Like those data types, the priority queue supports adding and removing an item from a collection. Unlike those data types, the order in which items are removed does not depend on the order in which they are added, but rather depends on a priority which is specified when each item is added.

A classic example of priority queues in practice is a hospital waiting room: more severe injuries and illnesses are generally treated before minor ones, regardless of when the patients arrived at the hospital.

Priority Queue ADT