# Lecture 15: Choose structures from operations and cost ## Choose operations before representation **Instructor:** [Dr. Debasish Pattanayak](https://drdebmath.github.io)
## An abstract data type specifies operations before representation A stack promises
push
,
pop
, and
top
. A queue promises
enqueue
,
dequeue
, and
front
. The contract does not require a class or one specific representation.
## Linear search is the trustworthy baseline when only traversal is known ~~~cpp std::vector
values{8, 3, 5, 3}; int target = 5; std::size_t found = values.size(); for (std::size_t i = 0; i < values.size() && found == values.size(); ++i) if (values[i] == target) found = i; ~~~ Worst case: inspect every element.
## Bubble sort trades simplicity for quadratic time ~~~cpp for (std::size_t end = values.size(); end > 1; --end) { for (std::size_t i = 1; i < end; ++i) { if (values[i] < values[i - 1]) { int temporary = values[i]; values[i] = values[i - 1]; values[i - 1] = temporary; } } } ~~~
## A stack returns the most recently pushed item first With an array representation, keep one integer
top
: - push: check capacity, then advance and store; - pop: check emptiness, read, then retreat; - top: inspect without removing. An undo history and function calls are stack applications.
## A queue returns the earliest enqueued item first A circular array keeps
front
,
rear
, and
count
. A linked queue keeps pointers to the first and last nodes. Print jobs and breadth-first exploration are queue applications.
## Compare structures by operation costs, not names | Requirement | Useful choice | |---|---| | scan unsorted readings | array + linear search | | undo most recent action | stack | | serve arrival order | queue | | repeatedly exchange adjacent inversions | array + bubble sort |
## Match operations, invariants, and cost before choosing a structure - An ADT is defined by valid operations and behavior. - Algorithms are applications of the representation's operations. - Linear search needs no ordering. - Stack means LIFO; queue means FIFO. - Bubble sort is simple but performs quadratic work.