The Set
This chapter covers the Set ADT, a collection of distinct items with no order. We implement it with a linked list, an unsorted array, and a sorted array, and speed up search in the unsorted versions with the move-to-front and transpose heuristics.
After reading this chapter, you should be able to:
- Describe the Set ADT: the
add,remove,contains, andsizeoperations, the boolean thataddandremovereturn to report whether the call changed the set, the rejection ofnull, and the absence of any positional operation - Implement and trace
LinkedSet, a singly linked list with asizefield, andArraySet, a backing array that removes with swap-with-last because a set promises no order - Explain why both unsorted implementations leave
contains,add, andremoveat , and compare them in time and memory - Implement the move-to-front and transpose heuristics to speed up search under skewed access, and explain why reordering a set on a read is safe
- Design a sorted-array set whose
containsis , and explain why sorting helps an array but not a linked list
You can download the accompanying code for this chapter: starter and solution.
Sections
- Choosing a Username
- The Set ADT
- Set ADT Specification
- Using a Linked List to Implement a Set
- The LinkedSet Class
- Implementing contains, add, and remove
- Tracing the LinkedSet
- Using an Array to Implement a Set
- The ArraySet Class
- Implementing contains, add, and remove
- Tracing the ArraySet
- The Move-to-Front Heuristic
- The Transpose Heuristic
- Using a Sorted Array to Implement a Set