BSCS and BSSE students can use this guide to study “Data Structures and Algorithm Analysis” (Java Version, Edition 3.2) by Clifford A. Shaffer of the Department of Computer Science at Virginia Tech. The author offers it free from his own web page. It covers the standard Data Structures and Algorithms syllabus in 17 chapters: algorithm analysis, lists, stacks, queues, trees, sorting, searching, hashing, indexing and graphs, followed by a final part on lower bounds, dynamic programming and NP-completeness. All code examples are in Java, and a C++ version of the same book is on the official page.
Every structure in the book is judged by its costs and benefits, with time and space worked out for each one, which is exactly what exam questions ask for. Be aware of one thing: the author now calls this PDF edition obsolete and recommends his online OpenDSA project, mainly because it adds visualisations and interactive exercises. The text, last updated on 28 March 2013, still teaches the fundamentals well. What has dated is limited to hardware figures from about 2011, an old benchmark machine and Java code that predates Java 8.
Book Overview
| Course | Data Structures and Algorithms (Algorithm Analysis) |
| Degree Programs | BSCS, BSSE |
| Level | University / Undergraduate (sophomore to senior level, as described in the preface) |
| Edition | Edition 3.2, Java Version (update 3.2.0.10, March 28, 2013) |
| Author | Clifford A. Shaffer, Department of Computer Science, Virginia Tech |
| Print Edition | Dover Publications |
| Programming Language | Java (a C++ version of the same book is also on the official page) |
| Structure | 17 chapters in 5 parts, plus bibliography and index |
| Exercises | Over 450 exercises and programming-project suggestions, according to the preface |
| Source Code | Java source files are offered on the author’s page (last updated May 20, 2011) |
| Language | English |
| Format | PDF (601 pages) — free from the author’s page |
Chapter List
Chapter 1: Data Structures and Algorithms
Part I: Preliminaries · Difficulty: Easy · Key topics: costs and benefits, resource constraints, abstract data type, encapsulation, design patterns, problem vs algorithm vs program
The chapter states the book’s three goals: present the common data structures, show that each one has costs and benefits, and teach how to measure them. It gives a three-step way to choose a structure: list the operations the problem needs, quantify the resource limits on each, then pick the structure that fits, using a bank account database (hash table) and a city database with range queries (B+-tree) as examples. It then separates types, abstract data types and data structures, introduces the Flyweight, Visitor, Composite and Strategy patterns, and ends by distinguishing a problem, an algorithm and a program.
Key Points:
- A solution is efficient if it solves the problem within the required resource constraints; cost is usually measured in time or space.
- Selecting a structure means analysing the basic operations (insert, delete, find), quantifying the constraints on each, and then choosing the structure that meets them.
- Three guiding questions: are all items inserted at the start (static) or mixed with other operations, can items be deleted, and is access in a fixed order or by search.
- An abstract data type (ADT) is a type plus its operations, with the implementation hidden; the data structure is the implementation of the ADT.
- Hashing is excellent for exact-match queries but hopeless for range queries, while the B+-tree handles both.
- An algorithm must be correct, made of concrete steps, have one starting point, and finish in finite time.
Practice Tip: Write down an ADT for a to-do list (insert, remove, find, size) without any code, then sketch two different implementations. You will see why the same ADT can have different costs.
Common Mistake: Treating a faster computer as a substitute for a better data structure. The chapter argues the opposite: bigger machines mean bigger problems, so efficiency matters more, not less.
Important Questions:
- What is the difference between an ADT and a data structure? The ADT is the logical definition (a type and its operations); the data structure is the physical implementation of that definition.
- How do you choose a data structure for a problem? Identify the basic operations, quantify the resource constraints on each, and select the structure whose costs fit them.
Chapter 2: Mathematical Preliminaries
Part I: Preliminaries · Difficulty: Medium · Key topics: sets, relations, logarithms, summations, recurrences, recursion, induction, proof by contradiction, estimation
This chapter is a review of the mathematics the later chapters lean on. It starts with sets, sequences and equivalence relations, then notation such as factorials, Stirling’s approximation, permutations and the floor and ceiling functions, before covering logarithm rules, summations and recurrences with closed forms. Recursion is taught through the Towers of Hanoi and a random permutation generator, and proof techniques (direct proof, contradiction and induction) get worked examples. It closes with back-of-the-envelope estimation, a three-step method with examples such as bookcases needed for a million pages.
Key Points:
- A set has no duplicates; a sequence is ordered and may repeat; a relation is an equivalence relation if it is reflexive, symmetric and transitive.
- The minimum number of bits needed to give n objects distinct codes is the ceiling of
log n; in this booklog nmeans base 2 unless stated. - The sum of the first n integers is
n(n+1)/2, and the sum of powers of two up to2^log nequals2n - 1. - A recursive function needs a base case and recursive calls on strictly smaller problems; the Towers of Hanoi uses two recursive calls.
- Induction needs a base case, an induction hypothesis and an induction step; it proves that a recursive function is correct.
- Estimation has three steps: find the major parameters, write an equation for them, then plug in values; check it a second way if you can.
Practice Tip: Write the recursive Towers of Hanoi function and print the moves for three rings, then four. Count the moves and you will see the doubling pattern the chapter asks about.
Common Mistake: Skipping the base case in an induction proof or a recursive function. Without it the argument or the program never gets started, or never stops.
Important Questions:
- What are the two parts of a recursive algorithm? A base case that is solved directly, and one or more recursive calls on smaller versions of the problem.
- How does proof by mathematical induction work? Prove the base case, assume the claim for smaller values (the induction hypothesis), and show that it then holds for the next value.
Chapter 3: Algorithm Analysis
Part I: Preliminaries · Difficulty: Hard · Key topics: growth rate, best, worst and average case, big-Oh, Omega, Theta, simplifying rules, space bounds, code tuning
The chapter explains why comparing programs by timing them is unreliable and replaces it with asymptotic analysis, which describes how cost grows with input size. It shows how a computer ten times faster helps a linear algorithm far more than a quadratic one, then defines upper bounds (big-Oh), lower bounds (Omega) and Theta, with rules for simplifying running-time equations. Sequential search and binary search illustrate best, worst and average cases, and the chapter covers analysing loops, whole problems, multiple parameters, space and the space/time tradeoff, a list of common misunderstandings, code-tuning advice and empirical measurement.
Key Points:
- Constant factors never change the relative gain from a faster computer: on a machine ten times faster, a linear algorithm handles ten times more data,
2n^2only about 3.16 times, and2^njust 3 more items. - Big-Oh gives an upper bound on the growth rate, Omega a lower bound, and Theta is used when the two meet.
- Upper and lower bounds describe what we know about a growth rate; best, worst and average case describe which inputs are measured. They are not the same thing.
- Simplifying rules: drop lower-order terms and constants, and the largest growth rate in a sum or sequence dominates.
- Sequential search is Θ(n) on average and in the worst case; binary search on a sorted array is Θ(log n).
- The space/time tradeoff principle says you can often save time by spending space, as a lookup table does.
Practice Tip: Time a nested loop for n = 1000, 2000 and 4000 and plot the results. Doubling n should roughly quadruple the time for a quadratic loop, which makes the growth rate visible.
Common Mistake: Equating big-Oh with the worst case and Omega with the best case. The case chooses which inputs you measure; the notation says how well you know the growth rate.
Important Questions:
- What is the difference between O, Omega and Theta? O is an upper bound on the growth rate, Omega is a lower bound, and Theta means both bounds are the same growth rate.
- Why is asymptotic analysis preferred over timing programs? It does not depend on the programmer, the test data or the machine, and it can show whether any algorithm could meet the budget before you write code.
Chapter 4: Lists, Stacks, and Queues
Part II: Fundamental Data Structures · Difficulty: Medium · Key topics: list ADT, array-based list, linked list, header node, freelist, doubly linked list, stack, queue, dictionary
The chapter defines the list as a finite ordered sequence with a notion of current position, then builds two implementations, the array-based list and the linked list, and compares their time and space costs with a break-even formula. It covers header nodes, freelists and doubly linked lists, then the stack and queue as restricted lists, each with array-based and linked versions, and shows how a stack implements recursion through activation records. The array-based queue is made efficient with a circular layout. The chapter ends with the dictionary ADT, built first on sorted and unsorted lists.
Key Points:
- The array-based list has constant-time access by position but Θ(n) insertion and deletion because elements shift; a linked list reverses that trade.
- A linked list needs one extra pointer per node; the break-even point depends on array size D, element size E and pointer size P.
- A header node removes special cases for an empty list; a freelist reuses released nodes instead of calling
neweach time. - A stack gives last-in first-out access (
push,pop); a queue gives first-in first-out (enqueue,dequeue). - A circular array queue needs n+1 distinct states, so one slot is left unused to tell empty from full.
- The dictionary ADT stores key-value records and offers insert, remove,
removeAnyand find.
Practice Tip: Implement a singly linked list with a header node, then insert and remove at the middle. Try the same without the header node and notice the extra empty-list cases.
Common Mistake: Letting the elements of an array queue drift toward the end of the array, or shifting every element on each dequeue (which costs Θ(n)). Use a circular array with modulo arithmetic instead.
Important Questions:
- When is an array-based list better than a linked list? When the size is predictable and the array is mostly full, or when you need fast access by position, since there is no pointer overhead.
- How are stacks used to implement recursion? Each call pushes an activation record (return address, parameters, local variables) and each return pops it.
Chapter 5: Binary Trees
Part II: Fundamental Data Structures · Difficulty: Medium · Key topics: binary tree terminology, full binary tree theorem, traversals, node implementations, binary search tree, heap, priority queue, Huffman coding tree
The chapter starts from the weakness of lists, where search or insertion is fast but not both, and presents binary trees. After the definitions and the Full Binary Tree Theorem, it covers preorder, inorder and postorder traversals, pointer-based node classes, the space overhead of different designs, and the array layout for complete trees. Three major applications follow: the binary search tree as a dictionary, the heap as a priority queue with sift-down and linear-time heap building, and Huffman coding trees that give frequent characters shorter prefix codes.
Key Points:
- Full Binary Tree Theorem: a non-empty full binary tree has one more leaf than it has internal nodes; a binary tree with n nodes has n+1 empty subtrees.
- Preorder visits the root first, inorder visits left, root, then right, and postorder visits the root last; each costs Θ(n).
- A BST keeps smaller values on the left, and an inorder traversal prints its nodes in sorted order.
- BST operations cost Θ(log n) when the tree is balanced, but a tree built from sorted input degenerates to Θ(n).
- A heap is a complete binary tree with the heap property;
buildHeaptakes Θ(n) whileremovemaxand insert take Θ(log n). - Huffman codes satisfy the prefix property, so no code is the prefix of another and decoding is unambiguous.
Practice Tip: Insert the keys 1 to 7 in order into a BST and then in the order 4, 2, 6, 1, 3, 5, 7. Compare the heights to see why insertion order matters.
Common Mistake: Assuming a BST is always fast. Its shape depends on insertion order, so sorted input gives a linked list in disguise.
Important Questions:
- What is a heap and what is it used for? A complete binary tree where every node is greater than (max-heap) or less than (min-heap) its children, used to implement priority queues and Heapsort.
- How are Huffman codes built? Repeatedly join the two lowest-weight subtrees into a new tree, then read each code from the path (0 for left, 1 for right) to its leaf.
Chapter 6: Non-Binary Trees
Part II: Fundamental Data Structures · Difficulty: Medium · Key topics: general trees, parent pointer implementation, UNION/FIND, weighted union, path compression, left-child/right-sibling, K-ary trees, sequential tree representations
Organisation charts need nodes with any number of children, so the chapter generalises binary trees. After the terminology and general tree traversals, it presents the parent pointer implementation and uses it to solve the equivalence class problem with UNION and FIND, improved by the weighted union rule and path compression. It then compares implementations: list of children, left-child/right-sibling and dynamic nodes. K-ary trees follow, carrying over the binary tree properties, and the chapter ends with sequential tree representations that save pointers and serialise trees for storage on disk.
Key Points:
- A general tree node can have any number of children; a forest is a collection of trees.
- The parent pointer tree stores only each node’s parent, which is exactly what UNION/FIND needs.
- Weighted union attaches the smaller tree under the larger one, and path compression flattens the tree during FIND.
- With both improvements, n UNION/FIND operations cost about Θ(n log* n), which is nearly constant per operation.
- The left-child/right-sibling implementation converts a general tree into a binary tree.
- Sequential representations save pointer space but give up fast access to arbitrary nodes.
Practice Tip: Code UNION/FIND on an array of parents and process a list of equivalence pairs. Print the array after each step, once with plain union and once with weighted union and path compression.
Common Mistake: Doing path compression during UNION. It belongs in FIND, where the nodes on the path to the root are already being visited.
Important Questions:
- What is the equivalence class problem? Given pairs of objects declared equivalent, decide whether two objects are in the same class; UNION/FIND solves it with parent pointer trees.
- What does the weighted union rule do? It joins the smaller tree beneath the root of the larger tree, which keeps tree depth small.
Chapter 7: Internal Sorting
Part III: Sorting and Searching · Difficulty: Medium · Key topics: stability, insertion sort, bubble sort, selection sort, Shellsort, Mergesort, Quicksort, Heapsort, Radix Sort, sorting lower bound
Sorting is used here to show several algorithm design ideas at once. After terminology (keys, stability, comparing by counting comparisons and swaps), the chapter covers three Θ(n²) sorts and proves that sorts which only swap adjacent items need Ω(n²) on average because of inversions. Shellsort exploits the best case of insertion sort, Mergesort splits by position, Quicksort splits by pivot value, Heapsort uses a max-heap, and Binsort and Radix Sort avoid comparisons altogether. A timing table compares every algorithm, and a decision-tree argument proves that comparison sorting needs Ω(n log n).
Key Points:
- Insertion Sort is Θ(n) on sorted input and Θ(n²) on average and worst; Bubble Sort is slower and, in the author’s words, has no redeeming features.
- Shellsort sorts virtual sublists with shrinking increments; increments built by division by three give about O(n^1.5) on average.
- Mergesort and Heapsort are Θ(n log n) in every case; Mergesort needs an auxiliary array, while Heapsort builds a heap in Θ(n) and then removes the maximum n times.
- Quicksort picks a pivot and partitions around it; it is Θ(n²) in the worst case but Θ(n log n) on average.
- Radix Sort handles keys digit by digit using bins and costs Θ(nk + rk) for k digits and radix r.
- Any sort that works by comparing keys needs Ω(n log n) comparisons in the worst case, because a decision tree must have n! leaves.
- The timing table was run on a 3.4-GHz Pentium 4, so read the ranking of the algorithms and not the milliseconds.
Practice Tip: Implement insertion sort, Quicksort and Mergesort and time them on random arrays of 10,000 and 100,000 integers. Then give them already-sorted input and see which ones change.
Common Mistake: Always using the first element as the Quicksort pivot. On sorted or nearly sorted data every partition is lopsided, and the sort slides to Θ(n²).
Important Questions:
- What is a stable sorting algorithm? One that does not change the relative order of records with equal key values.
- Why can no comparison-based sort beat n log n? Its decision tree needs at least n! leaves, so its depth is at least log n!, which is Ω(n log n).
Chapter 8: File Processing and External Sorting
Part III: Sorting and Searching · Difficulty: Medium · Key topics: primary vs secondary storage, disk drives, seek time, buffer pools, LRU, files in Java, external sorting, replacement selection, multiway merge
When data does not fit in memory, the cost of reaching the disk shapes every design choice. The chapter compares primary and secondary storage by price, persistence and access time (about six orders of magnitude slower for disk in its 2011 numbers), then explains platters, tracks, sectors, clusters and the three parts of a disk access: seek, rotational delay and transfer. Buffer pools with FIFO, LFU and LRU replacement are explained with worked virtual-memory examples and two buffer pool interfaces, followed by Java’s random-access file model. External sorting builds sorted runs, using replacement selection to get runs about twice memory size, and merges them with multiway merging.
Key Points:
- Disk access time is dominated by the seek; reading sectors in sequence avoids most seeks, so a program should keep a file’s sectors together.
- A buffer pool keeps recently used disk blocks in memory; LRU is usually the method of choice, and a dirty bit says whether a block must be written back.
- Internal fragmentation wastes space at sector and cluster boundaries, so cluster size is a tradeoff between wasted space and speed for large files.
- Replacement selection uses a heap to create initial runs of about 2M records on average, where M is the memory size in records (the snowplow argument).
- A two-way merge needs log R passes for R runs; multiway merging cuts the passes by reading several runs at once.
- The price tables and disk specifications are from 2011, but the book notes that the memory-to-disk ratios have stayed about the same for decades.
Practice Tip: Write a small program that reads a large file once sequentially and once by jumping to random positions with RandomAccessFile. Compare the times to feel the cost of seeks.
Common Mistake: Designing a disk-based program as if disk reads were as cheap as array accesses. The chapter’s whole point is that the number of disk accesses, not the number of instructions, decides the speed.
Important Questions:
- What are the three components of a disk access? Seek time to move the head to the track, rotational delay for the sector to arrive, and transfer time to read the data.
- How does external sorting work? First create sorted runs (for example with replacement selection), then merge the runs, ideally with a multiway merge to reduce the number of passes.
Chapter 9: Searching
Part III: Sorting and Searching · Difficulty: Medium · Key topics: exact-match and range queries, binary search, jump search, self-organizing lists, Zipf distribution, bit vectors, hash functions, collision resolution, load factor
Searching is defined as finding records with a key value, either by exact match or by range. The chapter handles sequential and sorted-array search, including jump search and dictionary (interpolation) search. It then shows how self-organizing lists use the 80/20 rule and Zipf distributions, comparing count, move-to-front and transpose heuristics, and uses bit vectors for sets. The longest part is hashing: hash functions such as mod, mid-square and string folding, separate chaining, bucket hashing, linear, pseudo-random and quadratic probing, double hashing, cost analysis by load factor, and deletion with tombstones.
Key Points:
- An exact-match query asks for one key; a range query asks for all keys in an interval, and hashing cannot support the latter efficiently.
- Many real access patterns follow the 80/20 rule (a Zipf distribution), so ordering a list by access frequency can speed up search.
- Move-to-front keeps recently used records near the head; the transpose heuristic swaps a found record one step forward.
- A good hash function spreads keys evenly over the table; the book covers modulo, mid-square and folding (
sfoldfor strings). - Linear probing suffers from primary clustering, which pseudo-random probing, quadratic probing and double hashing reduce.
- The load factor is α = N/M; expected cost grows as the table fills, and deleting from a closed hash table needs a tombstone so later searches do not stop early.
Practice Tip: Insert the same 20 keys into a small table with linear probing and then with double hashing. Print the table and the probe counts and you will see clustering appear.
Common Mistake: Marking a deleted slot as plain empty in a closed hash table. A search for a key further along its probe sequence will stop at the gap and wrongly report that the key is missing.
Important Questions:
- What is the difference between open and closed hashing? Open hashing (separate chaining) stores colliding records in lists outside the table; closed hashing (open addressing) keeps every record in the table and probes for another slot.
- What is primary clustering? The tendency of linear probing to build long runs of occupied slots, which lengthens later probe sequences.
Chapter 10: Indexing
Part III: Sorting and Searching · Difficulty: Hard · Key topics: primary and secondary keys, linear index, ISAM, 2-3 tree, B-tree, B+-tree, node splitting, disk-based search
Hashing only answers exact-match questions, so this chapter builds disk-based structures that also handle range queries and ordered access. It defines entry-sequenced files, primary and secondary keys and the linear index with a second-level index in memory, then ISAM, an early IBM scheme whose overflow chains degrade with updates. Tree indexing leads to the 2-3 tree as a simple balanced search tree, then to the B-tree of order m and the B+-tree, which keeps records only in linked leaves. Splits, promotions and deletions are walked through, and the chapter ends with the cost analysis of B-trees.
Key Points:
- An index associates a key with the location of its record, so a database can keep several indexes without rearranging the data file.
- A linear index is a sorted array of key/pointer pairs; it is efficient to search but expensive to update.
- ISAM divides a sorted file among cylinders with overflow areas, which fails when there are many updates.
- A 2-3 tree node holds one or two keys, and all leaves stay at the same level, so the tree is always height balanced.
- A B-tree of order m splits full nodes and promotes a key upward, keeping every node (except the root) at least half full.
- The B+-tree stores records only in the leaves, links the leaves in a list for range queries, and is the variant that is actually used; search, insert and delete are Θ(log n) with a large base.
Practice Tip: Draw the B-tree of order four after inserting the keys 1 to 10 in order, showing each split. Doing it by hand makes the promotion rule easy to remember.
Common Mistake: Thinking a B-tree grows downward from the root. It grows upward: a split that reaches the root creates a new root, which is why all leaves stay at the same depth.
Important Questions:
- Why are B+-trees preferred over B-trees for databases? Records live only in the leaves, internal nodes can hold more keys, and the linked leaves make range queries and full ordered scans cheap.
- What properties define a 2-3 tree? Each node has one or two keys (two or three children), the search tree property holds, and all leaves are at the same level.
Chapter 11: Graphs
Part IV: Advanced Data Structures · Difficulty: Hard · Key topics: graph terminology, adjacency matrix, adjacency list, DFS, BFS, topological sort, Dijkstra, Prim, Kruskal, minimum-cost spanning tree
Graphs model networks, routes, schedules and relationships, and the chapter begins with terminology: directed and undirected graphs, weights, paths, cycles, DAGs, sparse and dense graphs. It compares the adjacency matrix and adjacency list with a graph ADT and Java implementations. Depth-first and breadth-first search are presented as traversals, with topological sorting for DAGs. Single-source shortest paths come from Dijkstra’s algorithm, in a linear-scan version and a priority-queue version, and minimum-cost spanning trees from Prim’s and Kruskal’s greedy algorithms, the latter using UNION/FIND from Chapter 6.
Key Points:
- The adjacency matrix needs Θ(|V|²) space; the adjacency list needs Θ(|V| + |E|), so lists suit sparse graphs and matrices suit dense ones.
- DFS and BFS visit every vertex and edge once, costing Θ(|V| + |E|) with adjacency lists; BFS uses a queue where DFS uses a stack or recursion.
- A topological sort orders the vertices of a DAG so every prerequisite comes first; it can be built from a DFS or from a queue of vertices with no remaining prerequisites.
- Dijkstra’s algorithm costs Θ(|V|² + |E|) with a linear scan and Θ((|V| + |E|) log |E|) with a priority queue.
- A minimum-cost spanning tree connects all the vertices with the least total edge weight; Prim grows one tree, Kruskal merges components edge by edge.
- Kruskal’s algorithm runs in Θ(|E| log |E|) in the worst case, and both MST algorithms are greedy.
Practice Tip: Store a small weighted graph as both an adjacency matrix and an adjacency list, then run BFS and Dijkstra from the same start vertex. The two outputs must match.
Common Mistake: Mixing up the shortest-path tree and the minimum spanning tree. Dijkstra minimises the distance from one source to each vertex, while an MST minimises the total weight of the whole tree.
Important Questions:
- When should you use an adjacency list instead of an adjacency matrix? For sparse graphs, where |E| is much smaller than |V|², since it saves space and lets algorithms visit only the real neighbours.
- How does Dijkstra’s algorithm find shortest paths? It keeps a distance estimate for every vertex and repeatedly processes the unvisited vertex with the smallest distance, updating its neighbours.
Chapter 12: Lists and Arrays Revisited
Part IV: Advanced Data Structures · Difficulty: Medium · Key topics: multilists, pure, reentrant and cyclic lists, sparse matrices, memory manager, first fit, best fit, worst fit, buddy system, garbage collection
This chapter returns to list-like structures that overcome limits of plain arrays and linked lists. Multilists allow sublists as elements and are classified as pure lists (trees), reentrant lists (DAGs) and cyclic lists (graphs), written in bracket notation. Sparse matrices are stored with orthogonal linked lists or the Yale representation so space depends on the number of non-zero entries. The longest part is memory management: a memory manager with handles, a freelist, internal and external fragmentation, the sequential-fit policies first, best and worst fit, the buddy system, and failure policies including compaction and garbage collection by reference counts or mark/sweep.
Key Points:
- A pure list is a tree, a reentrant list is a DAG (a sublist may be shared), and a cyclic list can contain loops.
- A sparse matrix stores only its non-zero values, so time and space should depend on the number of non-zero entries (NNZ), not on n².
- The Yale-style representation (Matlab uses a similar one) keeps three lists: the non-zero values in column-major order, where each column starts, and the row of each value.
- External fragmentation is free space too small to use; internal fragmentation is space wasted inside an allocated block.
- First fit takes the first block that is big enough, best fit the smallest block that is big enough, and worst fit the largest; some request sequences work for one policy and fail for the others.
- The buddy system allocates blocks in sizes of 2^k and merges a freed block with its buddy, trading internal fragmentation for speed.
- Garbage collection finds unreachable memory using reference counts or mark/sweep; reference counts cannot reclaim cyclic structures.
Practice Tip: Take a 1000 by 1000 matrix with only about 5000 non-zero entries and store it in the Yale form. Compare the size of the three lists with a full two-dimensional array.
Common Mistake: Assuming best fit is always the best sequential-fit policy. The chapter shows request sequences that first fit can serve but best fit cannot, and the reverse.
Important Questions:
- What is the difference between internal and external fragmentation? Internal fragmentation wastes space inside an allocated block; external fragmentation leaves free blocks that are too small to satisfy requests.
- How does mark/sweep garbage collection work? Mark every object reachable from program variables, then sweep through memory and free every unmarked object.
Chapter 13: Advanced Tree Structures
Part IV: Advanced Data Structures · Difficulty: Hard · Key topics: tries, key space decomposition, PATRICIA, AVL tree, rotations, splay tree, k-d tree, PR quadtree, spatial data structures
This chapter collects specialised trees and is meant partly as a source of larger programming projects, so it gives descriptions rather than full code. Tries split the key range at predetermined positions instead of by stored values, which makes their shape independent of insertion order; binary tries and the PATRICIA variant are shown. The AVL tree and the splay tree are two ways of keeping a BST efficient, one by rotations that keep subtree heights within one of each other and the other by splaying accessed nodes to the root. The chapter ends with spatial structures for two-dimensional points: the k-d tree and the PR quadtree.
Key Points:
- A BST uses object space decomposition (its shape depends on the keys inserted); a trie uses key space decomposition, so its depth is limited by the key length.
- PATRICIA removes one-child chains from a binary trie by storing the bit position to test in each internal node.
- An AVL tree is a BST in which the subtree heights of every node differ by at most one, giving O(log n) search and update using single and double rotations.
- A splay tree has no balance rule; splaying a node to the root guarantees O(m log n) total time for m operations on n nodes (when m is at least n), not for each single operation.
- A k-d tree is a BST whose discriminator alternates between coordinates at each level, and it stores records at all nodes.
- A PR quadtree splits a region into four equal quadrants until each leaf holds at most one point, stores records only at leaves, and is a trie.
Practice Tip: Insert the keys 1 to 15 in order into a plain BST and into an AVL tree you code by hand. Compare the heights and mark where each rotation fires.
Common Mistake: Expecting every splay tree operation to be fast. Only the total cost of a series of operations is guaranteed; a single access can still take linear time.
Important Questions:
- What is the AVL tree balance property? For every node, the heights of its left and right subtrees differ by at most one, which keeps the depth at O(log n).
- How does a PR quadtree differ from a k-d tree? The PR quadtree uses key space decomposition and keeps data only in leaves; the k-d tree uses object space decomposition and keeps data at every node.
Chapter 14: Analysis Techniques
Part V: Theory of Algorithms · Difficulty: Hard · Key topics: summation techniques, guess and test, recurrence relations, expanding recurrences, divide and conquer recurrences, Master Theorem, amortized analysis
Some analyses are easy to set up and hard to solve, and this chapter collects the methods for solving them. For summations it shows how to estimate first and then find a closed form by guess-and-test, shifting, divide-and-guess and geometric series. Recurrences are solved by estimating bounds and proving them by induction, by expanding the recurrence into a summation, and by a theorem for divide-and-conquer recurrences, which covers Mergesort-style recurrences. The average-case recurrence for Quicksort is solved in full. Amortized analysis then treats a series of operations as a whole, with a stack example and the move-to-front heuristic.
Key Points:
- Estimating a sum first (the biggest term times the number of terms) gives a bound to test any proposed closed form against.
- Guess-and-test proposes a closed form, such as a polynomial of known degree, and then proves it by induction.
- Expanding a recurrence replaces smaller terms with their definitions until a summation with no recursion remains.
- The Master Theorem solves
T(n) = aT(n/b) + cn^k: Θ(n^(log_b a)) if a > b^k, Θ(n^k log n) if a = b^k, and Θ(n^k) if a < b^k. - Quicksort’s average-case recurrence solves to Θ(n log n).
- Amortized analysis gives the cost of a whole sequence, as with push and multipop on a stack, even if one operation is expensive.
Practice Tip: Apply the Master Theorem to the Mergesort recurrence T(n) = 2T(n/2) + n, then expand the same recurrence by hand. Both routes must give Θ(n log n).
Common Mistake: Using the Master Theorem on a recurrence that does not have the form aT(n/b) + cn^k, such as one that subtracts a constant from n. Expansion or induction is needed there.
Important Questions:
- What is amortized analysis? The analysis of a series of operations taken as a whole, which shows that the average cost per operation stays low even if some single operations are expensive.
- How do you solve a recurrence by expansion? Substitute the recurrence into itself repeatedly until a pattern appears, write the result as a summation, and find its closed form.
Chapter 15: Lower Bounds
Part V: Theory of Algorithms · Difficulty: Hard · Key topics: lower bound of a problem, searching, finding the maximum, adversary arguments, state space proofs, finding the ith best element, optimal sorting
An algorithm has to be judged against the inherent difficulty of its problem, so this chapter proves lower bounds from first principles. It starts with the “algorithm for finding algorithms” (propose an algorithm, prove a lower bound, repeat until they meet) and shows that searching an unsorted list needs n comparisons and a sorted list needs log n. Finding the maximum takes n-1 comparisons, and the second largest gets an exact answer through a binomial tree and an adversary proof. A state space argument bounds finding both the largest and smallest values, and the chapter closes with linear-time selection of the ith best element and the search for the fewest-comparison sort.
Key Points:
- The lower bound of a problem is the tightest bound provable for all algorithms; when it matches the best algorithm’s upper bound, the problem is fully understood.
- Finding the maximum of n unsorted values needs exactly n-1 comparisons.
- The second largest can be found in
n + ceil(log n) - 2comparisons by building a binomial tree of the winners. - An adversary argument imagines an opponent who answers each comparison to force as much work as possible.
- Finding both the largest and smallest values needs
ceil(3n/2) - 2comparisons. - The ith best value can be found in linear worst-case time using a pivot chosen as the median of medians of groups of five.
Practice Tip: Simulate a single-elimination tournament of 8 players on paper and list who could be second best. This is the idea behind the binomial tree algorithm.
Common Mistake: Committing the “necessity fallacy”: assuming that because your algorithm does something, every algorithm must. The chapter shows this exact error in a first, wrong proof about the second largest value.
Important Questions:
- How many comparisons are needed to find the maximum of n values? Exactly n-1, because every value except the maximum must lose at least one comparison.
- What is an adversary argument? A lower bound proof in which an imaginary adversary answers each comparison so as to make the algorithm do as much work as possible.
Chapter 16: Patterns of Algorithms
Part V: Theory of Algorithms · Difficulty: Hard · Key topics: dynamic programming, knapsack, Floyd’s algorithm, randomized algorithms, skip list, exponentiation, Euclid’s algorithm, Strassen, random numbers, FFT
The chapter presents algorithm design patterns that apply across many problems. Dynamic programming begins with the redundant recursive Fibonacci function, fixes it by storing sub-results, and then solves the knapsack problem and Floyd’s all-pairs shortest paths. Randomized algorithms are introduced through finding large values and the skip list, a probabilistic alternative to the BST. Numerical algorithms follow: fast exponentiation by halving, Euclid’s algorithm for the largest common factor, Strassen’s matrix multiplication, generating random numbers, and the Fast Fourier Transform, which speeds up polynomial multiplication.
Key Points:
- The plain recursive Fibonacci function recomputes the same values exponentially often; storing results in a table, or working bottom-up, makes it linear.
- Dynamic programming solves each subproblem once and stores the answer; the knapsack table algorithm costs Θ(nK).
- Floyd’s algorithm finds all-pairs shortest paths in Θ(|V|³) time regardless of the number of edges.
- A skip list is a probabilistic search structure whose levels are chosen at random, giving Θ(log n) average search, insertion and deletion without rebalancing.
- Exponentiation by repeated halving needs far fewer multiplications than multiplying n times.
- Strassen’s matrix multiplication runs in Θ(n^2.81) but only pays off for very large arrays.
Practice Tip: Count the calls made by the recursive Fibonacci function for n = 30, then run the table version. The huge difference is the whole argument for dynamic programming.
Common Mistake: Treating dynamic programming as just caching. The key step is identifying subproblems whose answers combine to give the full answer, as the knapsack formulation does.
Important Questions:
- What is dynamic programming? A technique that stores the solutions to subproblems in a table so that each is computed only once, avoiding the redundant work of plain recursion.
- Why is a skip list a probabilistic data structure? The level of each new node is chosen at random, so good performance comes from probability and not from the order of insertion.
Chapter 17: Limits to Computation
Part V: Theory of Algorithms · Difficulty: Hard · Key topics: reductions, hard problems, NP-completeness, SAT, travelling salesman, K-clique, coping strategies, uncountability, halting problem
The final chapter moves from analysing algorithms to analysing problems. Reductions are introduced with sorting and pairing, squaring and multiplication, and matrix multiplication, to transfer upper and lower bounds between problems. Hard problems are those needing exponential time, and the chapter explains why Towers of Hanoi is hard because of its output, then defines NP, NP-hard and NP-complete with the travelling salesman problem, K-clique and Cook’s SAT result, warning against reducing in the wrong direction. Ways of coping with NP-complete problems are listed, and the Halting Problem is proved unsolvable through an uncountability argument.
Key Points:
- A reduction converts instances of problem A into instances of problem B; it transfers upper bounds from B to A and lower bounds from A to B.
- A problem is NP-complete if it is in NP and every problem in NP reduces to it; whether P = NP is still unsolved.
- To prove a new problem NP-hard, reduce a known NP-hard problem to it; reducing the new problem to the known one is the common mistake.
- Cook proved SAT (Boolean satisfiability) NP-hard, so it became the starting point for all later NP-completeness proofs.
- Knapsack has a Θ(nK) dynamic programming algorithm, which is pseudo-polynomial because K can be exponential in the input size.
- The Halting Problem cannot be solved: there are more functions than programs, and the proof shows that no program can decide halting for all programs.
Practice Tip: Write the PAIRING-to-SORTING reduction in a few lines of code: sort the numbers and check neighbours. This makes the idea of using one problem as a tool for another concrete.
Common Mistake: Reducing the problem you are studying to a known NP-complete one and calling it NP-complete. The direction must be from the known hard problem to yours.
Important Questions:
- What does NP-complete mean? A problem that is in NP and to which every other problem in NP can be reduced in polynomial time, so a fast algorithm for it would solve them all.
- Why can the Halting Problem not be solved? The proof shows that a program able to decide halting for every program and input would lead to a contradiction.
How to Study This Book
The book has 17 chapters in five parts that the author declares himself: Part I Preliminaries (chapters 1 to 3), Part II Fundamental Data Structures (4 to 6), Part III Sorting and Searching (7 to 10), Part IV Advanced Data Structures (11 to 13) and Part V Theory of Algorithms (14 to 17). The preface says that once you have mastered chapters 1 to 6, the remaining material has relatively few dependencies, so those six chapters are the ones to read in order and not skip.
The preface also gives two reading plans. For a sophomore-level data structures course with little background, read chapters 1 to 11 in detail, plus selected topics from chapter 13. If you already did a CS2 course, read chapter 1, use chapter 2 only as a reference, go quickly through chapters 3 and 4, and spend your time on chapters 5 to 12. A senior-level algorithms course should focus on chapters 11 and 14 to 17. Pick the plan that matches your semester and do not feel obliged to read every page.
Chapter 3 is where most students struggle, and everything afterwards uses it, because every later structure is judged by its asymptotic cost. Take your time with Sections 3.4 to 3.7, especially the section on common misunderstandings, and do some of the exercises on growth rates before moving on. Chapter 2 is a review, so skim it, but read the recursion and induction sections properly if either idea is new to you, since chapters 4, 5 and 14 depend on them.
A few cross-chapter links matter. External sorting in chapter 8 needs the internal sorts of chapter 7 and the disk and buffer pool sections of the same chapter. Section 6.2 on UNION/FIND is used again in Kruskal’s algorithm in Section 11.5.2. Section 9.2 on self-organizing lists mentions the buffer replacement schemes of Section 8.3, and Section 17.2 relies on graphs from chapter 11. Chapter 14 pulls examples from the whole book, so leave it until you have met those structures.
Chapter 13 is intended in part as a source of larger programming projects. The author recommends that every data structures student implement some advanced tree or similar structure, such as a skip list or sparse matrix, and none of them is harder than a binary search tree once chapter 5 is done. Whatever you choose, type it in and test it. The code examples are illustrations tied to the text, and the preface warns that they are not commercial-quality classes and that you should not copy them directly into your own programs.
Know what the PDF does not give you. The author’s page now calls this PDF edition obsolete and recommends the online OpenDSA project, which adds visualisations and interactive exercises. Chapter 7’s timings come from a 3.4-GHz Pentium 4 and chapter 8’s disk and price figures are from 2011, so use them for the ratios and rankings and not as current numbers. The code is Java with generics but no lambdas, and the book builds its own list, stack and queue classes instead of using the Java library. Chapter 2 refers to “the Appendix” for the swap and random helpers, but this PDF has no appendix; those helper classes come with the source code on the author’s page. The PDF contains the exercises, and it does not include an answer key.
Used In These Programs
This book is used for the Data Structures and Algorithms course in: BS Computer Science · BS Software Engineering. Browse all Data Structures books, all Algorithms books or all Computer Science books.
Who Should Read This
This book is written for BSCS and BSSE students in a second data structures course or a first algorithms course. The preface expects two semesters of programming experience, including some exposure to Java, and says that readers who already know recursion have an advantage. A course in discrete mathematics helps too, although chapter 2 reviews the needed mathematics; if sets, induction or summations feel rusty, Discrete Mathematics: An Open Introduction is a good companion, and Think Java can fill gaps in Java itself. It is a teaching text and not an encyclopedia, so it covers most standard structures but not every one, and the author says he chose principles over memorising implementations. For the algorithms side, Algorithms by Dasgupta, Papadimitriou and Vazirani goes deeper on topics such as divide and conquer and linear programming. If your course uses C++, the C++ version of the same edition is on the official page, and Data Structures in C++ is another option. Students preparing for exams or technical interviews can use chapters 3 to 11 for the usual questions on complexity, trees, sorting, hashing and graphs.
Applicable Universities
This book is useful for students at Pakistani universities offering BS Computer Science or BS Software Engineering with a data structures or algorithms course, including Punjab University, Virtual University, COMSATS, FAST, UET, NUST, and other HEC-recognized institutions.
Official Copy of Data Structures and Algorithm Analysis
Professor Shaffer makes the Java version of Edition 3.2 available as a free PDF on his Virginia Tech page. The front page of the PDF allows free use for educational and non-commercial purposes and free electronic copying, while commercial use needs the author’s written consent. The official page also lists the C++ version, source code, errata and older updates. Click below to open the official page and choose the Java version.
→ Visit Official PageFAQs
Is Data Structures and Algorithm Analysis free?
Yes, it is free to download, but it is not under an open licence such as Creative Commons. The front page says the PDF is made freely available for educational and other non-commercial use. You may make copies and redistribute them in electronic form without charge, and you may extract portions as long as the front page, including the title, author and this notice, is included. Any commercial use needs the author’s written consent. Print copies are published by Dover Publications. Use the official page rather than reposting the file.
Which edition is this, and is there a C++ version?
This page covers Edition 3.2, Java Version, update 3.2.0.10, dated March 28, 2013, the latest PDF on the author’s page. The third edition first appeared in January 2010, and the version published by Dover is 3.2 from May 2011. A C++ version of the same edition, with the same 17 chapters, is a separate PDF on the same official page, so if your course uses C++ download that one instead.
How many chapters and exercises does it have?
There are 17 chapters in five parts, followed by a bibliography and an index; this PDF has no appendix. The preface says the book has over 450 exercises and suggestions for programming projects. The PDF does not include an answer key, but the author’s page also offers programming assignments, course notes and the Java source code.
Is it good for complete beginners?
Not for a first programming course. The preface expects two semesters of programming, including some exposure to Java, and recommends knowing recursion and having taken discrete mathematics. Chapter 2 reviews the mathematics, but the Java examples use classes, interfaces and generics without teaching them. If you are still learning Java, start with a beginner text and come back to this book for your data structures course.
Does it cover hashing, B+-trees, graph algorithms and NP-completeness?
Yes. Chapter 9 covers hash functions, chaining, probing and deletion with tombstones, chapter 10 covers ISAM, 2-3 trees, B-trees and B+-trees, chapter 11 covers DFS, BFS, topological sort, Dijkstra, Prim and Kruskal, and chapter 17 covers reductions, NP-completeness and the Halting Problem. Sorting is in chapters 7 and 8, including Mergesort, Quicksort, Heapsort, Radix Sort and external sorting.
Is it still current in 2026?
The core ideas are, but the format is not. The author’s own page calls this PDF edition obsolete and recommends the online OpenDSA project, which adds visualisations and interactive exercises. What has dated is limited: hardware prices and disk figures from 2011 in chapter 8, a Pentium 4 benchmark in chapter 7, and Java code that predates lambdas and builds its own container classes. Lists, trees, sorting, hashing, graphs, B-trees and NP-completeness are taught the same way today, so use it for the concepts and check current Java documentation for the library side.
Related Books
- Open Data Structures – Pat Morin (Java Edition)
- Think Data Structures: Algorithms and Information Retrieval in Java
- Algorithms – Dasgupta, Papadimitriou and Vazirani (DPV)
- Data Structures in C++ – Aikman Series
Data Structures and Algorithm Analysis gives you one free, consistent text that carries you from Big-Oh to NP-completeness, with the cost of every structure worked out. Browse more Computer Science books for the rest of your semester.
Data Structures and Algorithm Analysis, Edition 3.2 (Java Version, update 3.2.0.10, March 28, 2013) by Clifford A. Shaffer, Department of Computer Science, Virginia Tech. Copyright 2009–2012 Clifford A. Shaffer. The author makes the PDF freely available for educational and other non-commercial use; copies may be redistributed electronically without charge, portions may be extracted if the front page, title, author and notice are included, and any commercial use requires the author’s written consent. Print copies are published by Dover Publications. Official source: https://people.cs.vt.edu/shaffer/Book/. This page links to the official site and does not host or copy the book.
© Copyright Policy
Freebooks.pk is an educational resource for students in Pakistan. Textbooks and other books belong to their respective boards, authors and publishers, and all rights remain with them. If you are the copyright holder of any material on this page and want it changed or removed, please contact us or file a request under our DMCA policy. We review every request and remove reported content promptly.
