Docsity

Course Introduction and Background - Data Structures | CMSC 420, Study notes of Data Structures and Algorithms

Toggle sidebar
bg1
Lecture Notes CMSC 420
CMSC 420: Data Structures1
Spring 2001
Dave Mount
Lecture 1: Course Introduction and Background
(Tuesday, Jan 30, 2001)
Algorithms and Data Structures: The study of data structures and the algorithms that ma-
nipulate them is among the most fundamental topics in computer science. Most of what
computer systems spend their time doing is storing,accessing, and manipulating data in one
form or another. Some examples from computer science include:
Networking: Suppose you need to multicast a message from one source node to many other
machines on the network. Along what paths should the message be sent, and how can
this set of paths be determined from the network’s structure?
Information Retrieval: How does a search engine like Google store the contents of the Web
so that the few pages that are most relevant to a given query can be extracted quickly?
Compilers: You need to store a set of variable names along with their associated types.
Given an assignment between two variables we need to look them up in a symbol table,
determine their types, and determine whether it is possible to cast from one type to the
other (say because one is a subtype of the other).
Computer Graphics: You are designing a virtual reality system for an architectural building
walk-through. Given the location of the viewer, what portions of the architectural design
are visible to the viewer?
In many areas of computer science, much of the content deals with the questions of how to
store, access, and manipulate the data of importance for that area. In this course we will
deal with the first two tasks of storage and access at a very general level. (The last issue of
manipulation is further subdivided into two areas, manipulation of numeric or floating point
data, which is the subject of numerical analysis, and the manipulation of discrete data, which
is the subject of discrete algorithm design.) An good understanding of data structures is
fundamental to all of these areas.
What is a data structure? Whenever we deal with the representation of real world objects in
a computer program we must first consider a number of issues:
Modeling: the manner in which objects in the real world are modeled as abstract mathemat-
ical entities and basic data types,
Operations: the operations that are used to store, access, and manipulate these entities and
the formal meaning of these operations,
Representation: the manner in which these entities are represented concretely in a com-
puter’s memory, and
Algorithms: the algorithms that are used to perform these operations.
1Copyright, David M. Mount, 2001, Dept. of Computer Science, University of Maryland, College Park, MD, 20742.
These lecture notes were prepared by David Mount for the course CMSC 420, Data Structures, at the University of
Maryland, College Park. Permission to use, copy, modify, and distribute these notes for educational purposes and
without fee is hereby granted, provided that this copyright notice appear in all copies.
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download Course Introduction and Background - Data Structures | CMSC 420 and more Study notes Data Structures and Algorithms in PDF only on Docsity!

CMSC 420: Data Structures^1

Spring 2001

Dave Mount

Lecture 1: Course Introduction and Background

(Tuesday, Jan 30, 2001)

Algorithms and Data Structures: The study of data structures and the algorithms that ma- nipulate them is among the most fundamental topics in computer science. Most of what computer systems spend their time doing is storing, accessing, and manipulating data in one form or another. Some examples from computer science include:

Networking: Suppose you need to multicast a message from one source node to many other machines on the network. Along what paths should the message be sent, and how can this set of paths be determined from the network’s structure? Information Retrieval: How does a search engine like Google store the contents of the Web so that the few pages that are most relevant to a given query can be extracted quickly? Compilers: You need to store a set of variable names along with their associated types. Given an assignment between two variables we need to look them up in a symbol table, determine their types, and determine whether it is possible to cast from one type to the other (say because one is a subtype of the other). Computer Graphics: You are designing a virtual reality system for an architectural building walk-through. Given the location of the viewer, what portions of the architectural design are visible to the viewer?

In many areas of computer science, much of the content deals with the questions of how to store, access, and manipulate the data of importance for that area. In this course we will deal with the first two tasks of storage and access at a very general level. (The last issue of manipulation is further subdivided into two areas, manipulation of numeric or floating point data, which is the subject of numerical analysis, and the manipulation of discrete data, which is the subject of discrete algorithm design.) An good understanding of data structures is fundamental to all of these areas. What is a data structure? Whenever we deal with the representation of real world objects in a computer program we must first consider a number of issues:

Modeling: the manner in which objects in the real world are modeled as abstract mathemat- ical entities and basic data types, Operations: the operations that are used to store, access, and manipulate these entities and the formal meaning of these operations, Representation: the manner in which these entities are represented concretely in a com- puter’s memory, and Algorithms: the algorithms that are used to perform these operations. (^1) Copyright, David M. Mount, 2001, Dept. of Computer Science, University of Maryland, College Park, MD, 20742. These lecture notes were prepared by David Mount for the course CMSC 420, Data Structures, at the University of Maryland, College Park. Permission to use, copy, modify, and distribute these notes for educational purposes and without fee is hereby granted, provided that this copyright notice appear in all copies.

Note that the first two items above are essentially mathematical in nature, and deal with the “what” of a data structure, whereas the last two items involve the implementation issues and the “how” of the data structure. The first two essentially encapsulate the essence of an abstract data type (or ADT). In contrast the second two items, the concrete issues of implementation, will be the focus of this course. For example, you are all familiar with the concept of a stack from basic programming classes. This a sequence of objects (of unspecified type). Objects can be inserted into the stack by pushing and removed from the stack by popping. The pop operation removes the last unremoved object that was pushed. Stacks may be implemented in many ways, for example using arrays or using linked lists. Which representation is the fastest? Which is the most space efficient? Which is the most flexible? What are the tradeoffs involved with the use of one representation over another? In the case of a stack, the answers are all rather mundane. However, as data structures grow in complexity and sophistication, the answers are far from obvious. In this course we will explore a number of different data structures, study their implementa- tions, and analyze their efficiency (both in time and space). One of our goals will be to provide you with the tools that you will need to design and implement your own data structures to solve your own specific problems in data storage and retrieval.

Course Overview: In this course we will consider many different abstract data types, and we will consider many different data structures for storing each type. Note that there will generally be many possible data structures for each abstract type, and there will not generally be a “best” one for all circumstances. It will be important for you as a designer of data structures to understand each structure well enough to know the circumstances where one data structure is to be preferred over another. How important is the choice of a data structure? There are numerous examples from all areas of computer science where a relatively simple application of good data structure techniques resulted in massive savings in computation time and, hence, money. Perhaps a more important aspect of this course is a sense of how to design new data structures. The data structures we will cover in this course have grown out of the standard applications of computer science. But new applications will demand the creation of new domains of objects (which we cannot foresee at this time) and this will demand the creation of new data structures. It will fall on the students of today to create these data structures of the future. We will see that there are a few important elements which are shared by all good data structures. We will also discuss how one can apply simple mathematics and common sense to quickly ascertain the weaknesses or strengths of one data structure relative to another.

Algorithmics: It is easy to see that the topics of algorithms and data structures cannot be separated since the two are inextricably intertwined. So before we begin talking about data structures, we must begin with a quick review of the basics of algorithms, and in particular, how to measure the relative efficiency of algorithms. The main issue in studying the efficiency of algorithms is the amount of resources they use, usually measured in either the space or time used. There are usually two ways of measuring these quantities. One is a mathematical analysis of the general algorithm being used, called an asymptotic analysis, which can capture gross aspects of efficiency for all possible inputs but not exact execution times. The second is an empirical analysis of an actual implementation to determine exact running times for a sample of specific inputs, but it cannot predict the performance of the algorithm on all inputs. In class we will deal mostly with the former, but the latter is important also. There is another aspect of complexity, that we will not discuss at length (but needs to be considered) and that is the complexity of programming. Some of the data structures that we will discuss will be quite simple to implement and others much more complex. The issue

= lim n→∞

n

2 log n n^2

n^2.^5

Since this is a constant, we can assert that T (n) ∈ O(n^3 ). The O notation is good for putting an upper bound on a function. Notice that if T (n) is O(n^3 ) it is also O(n^4 ), O(n^5 ), etc. since the limit will just go to zero. We will try to avoid getting bogged down in this notation, but it is important to know the definitions. To get a feeling what various growth rates mean here is a summary.

T (n) ∈ O(1) : Great. This means your algorithm takes only constant time. You can’t beat this. T (n) ∈ O(log log n) : Super fast! For all intents this is as fast as a constant time. T (n) ∈ O(log n) : Very good. This is called logarithmic time. It is the running time of binary search and the height of a balanced binary tree. This is about the best that can be achieved for data structures based on binary trees. Note that log 1000 ≈ 10 and log 1, 000 , 000 ≈ 20 (log’s base 2). T (n) ∈ O((log n)k) : (where k is a constant). This is called polylogarithmic time. Not bad, when simple logarithmic time is not achievable. We will often write this as O(logk^ n). T (n) ∈ O(np) : (where 0 < p < 1 is a constant). An example is O(

n). This is slower than polylogarithmic (no matter how big k is or how small p), but is still faster than linear time, which is acceptable for data structure use. T (n) ∈ O(n) : This is called linear time. It is about the best that one can hope for if your algorithm has to look at all the data. (In data structures the goal is usually to avoid this though.) T (n) ∈ O(n log n) : This one is famous, because this is the time needed to sort a list of numbers. It arises in a number of other problems as well. T (n) ∈ O(n^2 ) : Quadratic time. Okay if n is in the thousands, but rough when n gets into the millions. T (n) ∈ O(nk) : (where k is a constant). This is called polynomial time. Practical if k is not too large. T (n) ∈ O(2n), O(nn), O(n!) : Exponential time. Algorithms taking this much time are only practical for the smallest values of n (e.g. n ≤ 10 or maybe n ≤ 20).

Lecture 2: Mathematical Prelimaries

(Thursday, Feb 1, 2001)

Read: Chapt 1 of Weiss and skim Chapt 2.

Mathematics: Although this course will not be a “theory” course, it is important to have a basic understanding of the mathematical tools that will be needed to reason about the data struc- tures and algorithms we will be working with. A good understanding of mathematics helps greatly in the ability to design good data structures, since through mathematics it is possible to get a clearer understanding of the nature of the data structures, and a general feeling for their efficiency in time and space. Last time we gave a brief introduction to asymptotic (big- “Oh” notation), and later this semester we will see how to apply that. Today we consider a few other preliminary notions: summations and proofs by induction.

Summations: Summations are important in the analysis of programs that operate iteratively. For example, in the following code fragment

for (i = 0; i < n; i++) { ... }

Where the loop body (the “...”) takes f (i) time to run the total running time is given by the summation

T (n) =

n∑− 1

i=

f (i).

Observe that nested loops naturally lead to nested sums. Solving summations breaks down into two basic steps. First simplify the summation as much as possible by removing constant terms (note that a constant here means anything that is independent of the loop variable, i) and separating individual terms into separate summations. Then each of the remaining simplified sums can be solved. Some important sums to know are

∑^ n

i=

1 = n (The constant series)

∑^ n

i=

i =

n(n + 1) 2

(The arithmetic series)

∑^ n

i=

i

= ln n + O(1) (The harmonic series)

∑^ n

i=

ci^ = cn+1^ − 1 c − 1

c 6 = 1 (The geometric series)

Note that complex sums can often be broken down into simpler terms, which can then be solved. For example

T (n) =

(^2) ∑n− 1

i=n

(3 + 4i) =

(^2) ∑n− 1

i=

(3 + 4i) −

n∑− 1

i=

(3 + 4i)

(^2) ∑n− 1

i=

(^2) ∑n− 1

i=

i

n∑− 1

i=

n∑− 1

i=

i

3(2n) + 4

2 n(2n − 1) 2

3(n) + 4

n(n − 1) 2

= (n + 6n^2 ).

The last summation is probably the most important one for data structures. For example, suppose you want to know how many nodes are in a complete 3-ary tree of height h. (We have not given a formal definition of tree’s yet, but consider the figure below. The height of a tree is the maximum number of edges from the root to a leaf.) One way to break this computation down is to look at the tree level by level. At the top level (level 0) there is 1 node, at level 1 there are 3 nodes, at level 2, 9 nodes, and in general at level i there 3 i^ nodes. To find the total number of nodes we sum over all levels, 0 through h. Plugging into the above equation with h = n we have:

∑^ h

i=

3 i^ =

3 h+1^ − 1 2

∈ O(3h).

= 9(3N (h − 3) + 1) + 3 + 1 = 27 N (h − 3) + 9 + 3 + 1 .. . = 3 kN (h − k) + (3k−^1 +... + 9 + 3 + 1)

When does this all end? We know that N (0) = 1, so let’s set k = h implying that

N (h) = 3hN (0) + (3h−^1 +... + 3 + 1) = 3h^ + 3h−^1 +... + 3 + 1 =

∑^ h

i=

3 i.

This is the same thing we saw before, just derived in a different way.

Proofs by Induction: The last mathematical technique of importance is that of proofs by induc- tion. Induction proofs are critical to all aspects of computer science and data structures, not just efficiency proofs. In particular, virtually all correctness arguments are based on induction. From courses on discrete mathematics you have probably learned about the standard approach to induction. You have some theorem that you want to prove that is of the form, “For all integers n ≥ 1, blah, blah, blah”, where the statement of the theorem involves n in some way. The idea is to prove the theorem for some basis set of n-values (e.g. n = 1 in this case), and then show that if the theorem holds when you plug in a specific value n − 1 into the theorem then it holds when you plug in n itself. (You may be more familiar with going from n to n + 1 but obviously the two are equivalent.) In data structures, and especially when dealing with trees, this type of induction is not par- ticularly helpful. Instead a slight variant called strong induction seems to be more relevant. The idea is to assume that if the theorem holds for all values of n that are strictly less than n then it is true for n. As the semester goes on we will see examples of strong induction proofs. Let’s go back to our previous example problem. Suppose we want to prove the following theorem.

Theorem: Let T be a complete 3-ary tree with n ≥ 1 nodes. Let H(n) denote the height of this tree. Then H(n) = (log 3 (2n^ + 1))^ −^1.

Basis Case: (Take the smallest legal value of n, n = 1 in this case.) A tree with a single node has height 0, so H(1) = 0. Plugging n = 1 into the formula gives (log 3 (2 · 1 + 1)) − 1 which is equal to (log 3 3) − 1 or 0, as desired. Induction Step: We want to prove the theorem for the specific value n > 1. Note that we cannot apply standard induction here, because there is no complete 3-ary tree with 2 nodes in it (the next larger one has 4 nodes). We will assume the induction hypothesis, that for all smaller n′, 1 ≤ n′^ < n, H(n′) is given by the formula above. (This is sometimes called strong induction, and it is good to learn since most induction proofs in data structures work this way.) Let’s consider a complete 3-ary tree with n > 1 nodes. Since n > 1, it must consist of a root node plus 3 identical subtrees, each being a complete 3-ary tree of n′^ < n nodes. How many nodes are in these subtrees? Since they are identical, if we exclude the root node, each subtree has one third of the remaining number nodes, so n′^ = (n − 1)/3. Since n′^ < n we can apply the induction hypothesis. This tells us that

H(n′) = (log 3 (2n′^ + 1)) − 1 = (log 3 (2(n − 1)/3 + 1)) − 1

= (log 3 (2(n − 1) + 3)/3) − 1 = (log 3 (2n + 1)/3) − 1 = log 3 (2n + 1) − log 3 3 − 1 = log 3 (2n + 1) − 2.

Note that the height of the entire tree is one more than the heights of the subtrees so H(n) = H(n′) + 1. Thus we have:

H(n) = log 3 (2n + 1) − 2 + 1 = log 3 (2n + 1) − 1 ,

as desired.

This may seem like an awfully long-winded way of proving such a simple fact. But induction is a very powerful technique for proving many more complex facts that arise in data structure analyses. You need to be careful when attempting proofs by induction that involve O(n) notation. Here is an example of a common error.

False! Theorem: For n ≥ 1, let T (n) be given by the following summation

T (n) =

∑^ n

i=

i,

then T (n) ∈ O(n). (We know from the formula for the linear series above that T (n) = n(n + 1)/ 2 ∈ O(n^2 ). So this must be false. Can you spot the error in the following “proof”?) Basis Case: For n = 1 we have T (1) = 1, and 1 is O(1). Induction Step: We want to prove the theorem for the specific value n > 1. Suppose that for any n′^ < n, T (n′) ∈ O(n′). Now, for the case n, we have (by definition)

T (n) =

∑^ n

i=

i =

(n− 1 ∑

i=

i

  • n = T (n − 1) + n.

Now, since n− 1 < n, we can apply the induction hypothesis, giving T (n−1) ∈ O(n−1). Plugging this back in we have

T (n) ∈ O(n − 1) + n.

But (n − 1) + n ≤ 2 n − 1 ∈ O(n), so we have T (n) ∈ O(n).

What is the error? Recall asymptotic notation applies to arbitrarily large n (for n in the limit). However induction proofs by their very nature only apply to specific values of n. The proper way to prove this by induction would be to come up with a concrete expression, which does not involve O-notation. For example, try to prove that for all n ≥ 1, T (n) ≤ 50 n. If you attempt to prove this by induction (try it!) you will see that it fails.

Lecture 3: A Quick Introduction to Java

(Tuesday, Feb 6, 2001)

Read: Chapt 1 of Weiss (from 1.4 to the end).

Disclaimer: I am still learning Java, and there is a lot that I do not know. If you spot any errors in this lecture, please bring them to my attention.

In Java you do not need to delete things created by new. It is up to the system to do garbage collection to get rid of objects that you no longer refer to. In Java a 2-dimension array is actually an array of arrays.

String Object: In C++ a string is implemented as an array of characters, terminated by a null character. Java has much better integrated support for strings, in terms of a special String object. For example, each string knows its length. Strings can be concatenated using the “+” operator (which is the only operator overloading supported in Java).

String S = "abc"; // S is the string "abc" String T = S + "def"; // T is the string "abcdef" char c = T[3]; // c = ’d’ S = S + T; // now S = "abcabcdef" int k = T.length(); // k = 6

Note that strings can be appended to by concatenation (as shown above with S). If you plan on making many changes to a string variable, there is a type StringBuffer which provides a more efficient method for “growable” strings. Java supports automatic casting of simple types into strings, which comes in handy for doing output. For example,

int cost = 25; String Q = "The value is " + cost + " dollars";

Would set Q to “The value is 25 dollars”. If you define your own object, you can define a method toString(), which produces a String representation for your object. Then any attempt to cast your object to a string will invoke your method. There are a number of other string functions that are supported. One thing to watch out for is string comparison. The standard == operator will not do what you might expect. The reason is that a String object (like all objects in Java) behaves much like a pointer or reference does in C++. Comparisons using == test whether the pointers are the same, not whether the contents are the same. The equals() or compareTo() methods to test the string contents.

Flow Control: All the standard flow-control statements, if-then-else, for, while, switch, continue, etc., are the same as in C++.

Standard I/O: Input and output from the standard input/output streams are not quite as simple in Java as in C++. Output is done by the print() and println() methods, each of which prints a string to the standard output. The latter prints an end-of-line character. In Java there are no global variables or functions. Everything is referenced as a member of some object. These functions exist as part of the System.out object. Here is an example of its usage.

int age = 12; System.out.println("He is " + age + " years old");

Input in Java is much messier. Since our time is limited, we’ll refer you to our textbook (by Weiss) for an example of how to use the java.io.BufferedReader, java.io.InputStream- Reader, StringTokenizer to input lines and read them into numeric, string, and character variables.

Classes and Objects: Virtually everything in Java is organized around the notion of hierarchy of objects and classes. As in C++ an object is an entity which stores data and provides methods for accessing and modifying the data. An object is an instance of a class, which defines the specifics of the object. As in C++ a class consists of instance variables and methods. Although classes are superficially similar to classes in C++, there are some important differences in how they operate.

File Structure: Java differs from C++ in that there is a definite relationship between files and classes. Normally each Java class resides within its own file, whose name is de- rived from the name of the class. For example, a class Student would be stored in file Student.java. Unlike C++, in which class declarations are stored in different files (.h and .cc), in Java everything is stored in the same file and all definitions are made within the class. Packages: Another difference with C++ is the notion of packages. A package is a collection of related classes (e.g. the various classes that make up one data structure). The classes that make up a package are stored in a common directory (with the same name as the package). In C++ you access predefined objects using an #include command to load the definitions. In Java this is done by importing the desired package. For example, if you wanted to use the Stack data structure in the java.util library, you would load this using the following.

import java.util.Stack;

The Dot (.) Operator: Class members are accessed as in C++ using the dot operator. However in Java, objects all behave as if they were pointers (or perhaps more accurately as references that are allowed to be null).

class Person { String name; int age; public Person() {...} // constructor (details omitted) } Person p; // p has the value null p = new Person(); // p points to a new object Person q = p; // q and p now point to the same object p = null; // q still points to the object

Note that unlike C++ the declaration “Person p” did not allocate an object as it would in C++. It creates a null pointer to a Person. Objects are only created using the “new” operator. Also, unlike C++ the statement “q = p” does not copy the contents of p, but instead merely assigns the pointer q to point to the same object as p. Note that the pointer and reference operators of C++ (“*”, “&”, “->”) do not exist in Java (since everything is a pointer). While were at it, also note that there is no semicolon (;) at the end of the class definition. This is one small difference between Java and C++. Inheritance and Subclasses: As with C++, Java supports class inheritance (but only single not multiple inheritance). A class which is derived from another class is said to be a child or subclass, and it is said to extend the original parent class, or superclass. class Person { ... } class Student extends Person { ... }

The Student class inherits the structure of the Person class and can add new instance variables and new methods. If it redefines a method, then this new method overrides the

class Person { int age; public Person(int a) { age = a; } // Person constructor } class Student extends Person { String major; public Student(int a, String m) { // Student constructor super(a); // construct Person major = m; } }

(By the way, this is a dangerous way to initialize a String object, since recall that assign- ment does not copy contents, it just copies the pointer.)

Functions, Parameters, and Wrappers: Unlike C++ all functions must be part of some class. For example, the main procedure must itself be declared as part of some class, as a public, static, void method. The command line arguments are passed in as an array of strings. Since arrays can determine their own length from the length() method, there is no need to indicate the number of arguments. For example, here is what a typical Hello-World program would look like. This is stored in a file HelloWorld.java

class HelloWorld { public static void main(String args[]) { System.out.println("Hello World"); System.out.println("The number of arguments is " + args.length()); } }

In Java simple types are passed by value and objects are passed by reference. Thus, modifying an object which has been passed in through a parameter of the function has the effect of modifying the original object in the calling routine. What if you want to pass an integer to a function and have its value modified. Java provides a simple trick to do this. You simply wrap the integer with a class, and now it is passed by reference. Java efines wrapper classes Integer (for int), Long, Character (for char), Boolean, etc.

Generic Data Structures without Templates: Java does not have many of the things that C++ has, templates for example. So, how do you define a generic data structure (e.g. a Stack) that can contain objects of various types (int, float, Person, etc.)? In Java every class automatically extends a most generic class called Object. We set up our generic stack to hold objects of type Object. Since this is a superclass of all classes, we can store any objects from any class in our stack. Of course, to keep our sanity, we should store object of only one type in any given stack. (Since it will be very difficulty to figure out what comes out whenever we pop something off the stack.) Consider the ArrayVector class defined below. Suppose we want to store integers in this vector. An int is not an object, but we can use the wrapper class Integer to convert an integer into an object.

ArrayVector A = new ArrayVector(); A.insertAtRank(0, Integer(999)); // insert 999 at position 0 A.insertAtRank(1, Integer(888)); // insert 888 at position 1 Integer x = (Integer) A.elemAtRank(0); // accesses 999

Note that the ArrayVector contains Objects. Thus, when we access something from the data structure, we need to cast it back to the appropriate type.

// This is an example of a simple Java class, which implements a vector // object using an array implementation. This would be stored in a file // named "ArrayVector.java".

public class ArrayVector { private Object[] a; // Array storing the elements of the vector private int capacity = 16; // Length of array a private int size = 0; // Number of elements stored in the vector

// Constructor public ArrayVector() { a = new Object[capacity]; }

// Accessor methods public Object elemAtRank(int r) { return a[r]; }

public int size() { return size; }

public boolean isEmpty() { return size() == 0; }

// Modifier methods public Object replaceAtRank(int r, Object e) { Object temp = a[r]; a[r] = e; return temp; }

public Object removeAtRank(int r) { Object temp = a[r]; for (int i=r; i < size-1; i++) // Shift elements down a[i] = a[i+1]; size--; return temp; }

public void insertAtRank(int r, Object e) { if (size == capacity) { // An overflow capacity *= 2; Object[] b = new Object[capacity]; for (int i=0; i < size; i++) b[i] = a[i]; a = b; } for (int i=size-1; i>=r; i--) // Shift elements up a[i+1] = a[i]; a[r] = e; size++; } }

Lecture 4: Basic Data Structures

(Thursday, Feb 8, 2001)

Internal linked list External linked list

allocation

Sequential

head

a 1 a 2 a 3 a 4

a 1

a 2

a 3

a 4

head a 1 a 2 a 3 a 4

Figure 2: Common types of list allocation.

Multilists and Sparse Matrices: Although lists are very basic structures, they can be combined in various nontrivial ways. One such example is the notion of a multilist, which can be thought of as two sets of linked lists that are interleaved with each other. One application of multilists is in representing sparse matrices. Suppose that you want to represent a very large m × n matrix. Such a matrix can store O(mn) entries. But in many applications the number of nonzero entries is much smaller, say on the order of O(m+n). (For example, if n = m = 10, 000 this might means that only around 0.01% of the entries are being used.) A common approach for representing such a sparse matrix is by creating m linked lists, one for each row and n linked lists, one for each column. Each linked list stores the nonzero entries of the matrix. Each entry contains the row and column indices [i][j] as well as the value stored in this entry.

1 0

0 67

99

1 22 39

0 1 85

2

Columns

Rows

2 2

3

15 1 3

Matrix contents

Figure 3: Sparse matrix representation using multilists.

Stacks, Queues, and Deques: There are two very special types of lists: stacks and queues and their generalization, called the deque.

Stack: Supports insertions (called pushes) and deletions (pops) from only one end (called the top). Stacks are used often in processing tree-structured objects, in compilers (in processing nested structures), and is used in systems to implement recursion. Queue: Supports insertions (called enqueues) at one end (called the tail or rear) and deletions (called dequeues) from the other end (called the head or front). Queues are used in operating systems and networking to store a list of items that are waiting for some resource. Deque: This is a play on words. It is written like “d-e-que” for a “double-ended queue”, but it is pronounced like deck, because it behaves like a deck of cards, where you can deal off the top or the bottom. A deque supports insertions and deletions from either end. Clearly, given a deque, you immediately have an implementation of a stack or queue by simple inheritance.

Both stacks and queues can be implemented efficiently as arrays or as linked lists. There are a number of interesting issues involving these data structures. However, since you have probably seen these already, we will skip the details here.

Graphs: Intuitively, a graph is a collection of vertices or nodes, connected by a collection of edges. Graphs are extremely important because they are a very flexible mathematical model for many application problems. Basically, any time you have a set of objects, and there is some “con- nection” or “relationship” or “interaction” between pairs of objects, a graph is a good way to model this. Examples of graphs in application include communication and transportation networks, VLSI and other sorts of logic circuits, surface meshes used for shape description in computer-aided design and geographic information systems, precedence constraints in schedul- ing systems. The list of application is almost too long to even consider enumerating it.

Definition: A directed graph (or digraph) G = (V, E) consists of a finite set V , called the vertices or nodes, and E, a set of ordered pairs, called the edges of G. (Another way of saying this is that E is a binary relation on V .)

Observe that self-loops are allowed by this definition. Some definitions of graphs disallow this. Multiple edges are not permitted (although the edges (v, w) and (w, v) are distinct).

1

2 3

Digraph

(^4 )

2

3

4

Graph

Figure 4: Digraph and graph example.

Definition: An undirected graph (or graph) G = (V, E) consists of a finite set V of vertices, and a set E of unordered pairs of distinct vertices, called the edges. (Note that self-loops are not allowed).

Note that directed graphs and undirected graphs are different (but similar) objects mathemat- ically. We say that vertex v is adjacent to vertex u if there is an edge (u, v). In a directed graph, given the edge e = (u, v), we say that u is the origin of e and v is the destination of e. In undirected graphs u and v are the endpoints of the edge. The edge e is incident (meaning that it touches) both u and v. In a digraph, the number of edges coming out of a vertex is called the out-degree of that vertex, and the number of edges coming in is called the in-degree. In an undirected graph we just talk about the degree of a vertex as the number of incident edges. By the degree of a graph, we usually mean the maximum degree of its vertices. When discussing the size of a graph, we typically consider both the number of vertices and the number of edges. The number of vertices is typically written as n or V , and the number of edges is written as m or E. Here are some basic combinatorial facts about graphs and digraphs. We will leave the proofs to you. Given a graph with V vertices and E edges then:

In a graph:

  • 0 ≤ E ≤

(n 2

= n(n − 1)/ 2 ∈ O(n^2 ).

v∈V deg(v) = 2E.

1 0

1

1

1 2 3 1 2

1 0 0

Adjacency matrix Adjacency list (with crosslinks)

Adj 4

1

1 2 4

2 4

1 3

3

4

3

1

1 1

0

0

1 1 4 1 0

3

2

1

3

1

2 3

4

Figure 6: Adjacency matrix and adjacency list for graphs.

Lecture 5: Trees

(Tuesday, Feb 13, 2001)

Read: Chapt. 4 in Weiss.

Trees: Trees and their variants are among the most common data structures. In its most general form, a free tree is a connected, undirected graph that has no cycles. Since we will want to use our trees for applications in searching, it will be more meaningful to assign some sense of order and direction to our trees. Formally a tree (actually a rooted tree) is defined recursively as follows. It consists of one or more items called nodes. (Our textbook allows for the possibility of an empty tree with no nodes.) It consists of a distinguished node called the root, and a set of zero or more nonempty subsets of nodes, denoted T 1 , T 2 ,... , Tk, where each is itself a tree. These are called the subtrees of the root. The root of each subtree T 1 ,... , Tk is said to be a child of r, and r is the parent of each root. The children of r are said to be siblings of one another. Trees are typically drawn like graphs, where there is an edge (sometimes directed) from a node to each of its children. See the figure below.

... F

I

D

T 1 T 2 T k

A

B C

E

H

G

r

Figure 7: Trees.

If there is an order among the Ti’s, then we say that the tree is an ordered tree. The degree of a node in a tree is the number of children it has. A leaf is a node of degree 0. A path between two nodes is a sequence of nodes u 1 , u 2 ,... , uk such that ui is a parent of ui+1. The length of a path is the number of edges on the path (in this case k − 1). There is a path of length 0 from every node to itself.

The depth of a node in the tree is the length of the unique path from the root to that node. The root is at depth 0. The height of a node is the length of the longest path from the node to a leaf. Thus all leaves are at height 0. If there is a path from u to v we say that v is a descendants of u. We say it is a proper descendent if u 6 = v. Similarly, u is an ancestor of v.

Implementation of Trees: One difficulty with representing general trees is that since there is no bound on the number of children a node can have, there is no obvious bound on the size of a given node (assuming each node must store pointers to all its children). The more common representation of general trees is to store two pointers with each node: the firstChild and the nextSibling. The figure below illustrates how the above tree would be represented using this technique.

firstChild

data nextSibling

root

C D

I

G

H

E F

B

A

Figure 8: A binary representation of general trees.

Trees arise in many applications in which hierarchies exist. Examples include the Unix file system, corporate managerial structures, and anything that can be described in “outline form” (like the chapters, sections, and subsections of a user’s manual). One special case of trees will be very important for our purposes, and that is the notion of a binary tree.

Binary Trees: Our text defines a binary tree as a tree in which each node has no more than two children. However, this definition is subtly flawed. A binary tree is defined recursively as follows. A binary tree can be empty. Otherwise, a binary tree consists of a root node and two disjoint binary trees, called the left and right subtrees. The difference in the two definitions is important. There is a distinction between a tree with a single left child, and one with a single right child (whereas in our normal definition of tree we would not make any distinction between the two). The typical Java representation of a tree as a data structure is given below. The element field contains the data for the node and is of some abstract type, which in Java might be Object. (In C++ the element type could be specified using a template.) When we need to be concrete we will often assume that element fields are just integers. The left field is a pointer to the left child (or null if this tree is empty) and the right field is analogous for the right child.

class BinaryTreeNode { Object element; // data item BinaryTreeNode left; // left child BinaryTreeNode right; // right child ... }

Binary trees come up in many applications. One that we will see a lot of this semester is for representing ordered sets of objects, a binary search tree. Another one that is used often in compiler design is expression trees which are used as an intermediate representation for expressions when a compiler is parsing a statement of some programming language. For