এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।
University Computer Science — Year 1 · স্নাতক প্রথম বর্ষ
14Dynamic Arrays and Amortised Analysis
A Python list grows by one element at a time, millions of times, and each append takes about the same short time however long the list already is. Yet a list lives in one block of memory, and a block cannot grow in place: when it is full, a larger block must be reserved and every element copied into it, which costs time proportional to the length. Both statements are true. The way out is to make the copies rare, and to count the cost of a long sequence of operations rather than of one: this is amortised analysis, and this chapter builds the growing array on which it works, in C, behind an interface that hides how it is made.
You already know
A C module is a header, which declares what its users may call, and a source file, which defines it; the users include the header only (Chapter 7). malloc reserves a block on the heap and free returns it (Chapter 4). A cost in is bounded by a constant independent of the input size (Chapter 13).
14.1 Abstract types and implementations
Definition 14.1 (Abstract data type)
An abstract data type is a type given by a set of operations and their specification, without saying how its values are represented. Its interface is the list of the operations with their signatures; an implementation chooses a representation and writes the operations. Code that uses only the interface works unchanged with any implementation that meets the specification.
Definition 14.2 (Constructor, accessor, transformer)
The operations of an abstract type are of three kinds: a constructor creates a value of the type, an accessor returns information about a value without changing it, and a transformer changes it.
// vec.h: the interface of the abstract type "dynamic array of int".
#ifndef VEC_H
#define VEC_H
#include <stddef.h>
typedef struct vec vec; // opaque: the fields stay in the implementation
vec *vec_new(void); // constructor: an empty array
void vec_free(vec *v);
size_t vec_size(const vec *v); // accessors
int vec_get(const vec *v, size_t i); // precondition: i < size
void vec_set(vec *v, size_t i, int x); // transformers; precondition: i < size
void vec_push(vec *v, int x); // add x at the end
int vec_pop(vec *v); // remove and return the last; precondition: size > 0
size_t vec_capacity(const vec *v); // for the experiments: cells reserved
long vec_copies(const vec *v); // for the experiments: elements copied so far
#endif
The declaration typedef struct vec vec; names a structure without giving its fields: a user can hold a vec * and pass it to the functions, but cannot read or change the fields, which are defined only in the implementation. The compiler enforces the interface. Two files implement it: vec.c, the growing array of this chapter, and fixed.c, an array of 16 cells that refuses a seventeenth element.
struct vec differ between the two files.$ gcc -std=c17 -O2 -Wall -Wextra vec_demo.c vec.c -o demo_vec
$ gcc -std=c17 -O2 -Wall -Wextra vec_demo.c fixed.c -o demo_fixed
$ ./demo_vec | sed -n '15,18p'
push 15: size 15 capacity 16 copies so far 15
push 16: size 16 capacity 16 copies so far 15
push 17: size 17 capacity 32 copies so far 31
sum of the elements: 153
$ ./demo_fixed 2>&1 | sed -n '15,18p'
push 15: size 15 capacity 16 copies so far 0
push 16: size 16 capacity 16 copies so far 0
vec: full at 16 elements
14.2 The doubling array
Definition 14.3 (Dynamic array, size and capacity)
A dynamic array stores a sequence in a block of memory larger than needed. Its size is the number of elements, its capacity the number of cells in the block. Adding an element to a full array first moves the elements to a larger block, whose capacity is a constant factor larger.
Definition 14.4 (Representation invariant)
A representation invariant is a condition on the fields of an implementation that every operation may assume on entry and must restore before returning. It says which values of the fields represent a value of the abstract type.
struct vec {
int *data;
size_t size, capacity;
long copies;
};
// representation invariant: 1 <= capacity, size <= capacity, data holds capacity
// cells, and size > capacity / 4 unless capacity == 1 or the array was just made
static void resize(vec *v, size_t capacity) {
int *data = malloc(capacity * sizeof *data);
if (data == NULL) {
perror("vec");
exit(1);
}
for (size_t i = 0; i < v->size; i++) data[i] = v->data[i];
v->copies += (long)v->size;
free(v->data);
v->data = data;
v->capacity = capacity;
}
void vec_push(vec *v, int x) {
if (v->size == v->capacity) resize(v, 2 * v->capacity);
v->data[v->size++] = x;
}
int vec_pop(vec *v) {
int x = v->data[--v->size];
if (v->capacity > 1 && v->size <= v->capacity / 4) resize(v, v->capacity / 2);
return x;
}
The capacity doubles when a push finds the array full, and halves when a pop leaves it a quarter full. Shrinking at a half would be a mistake (Section 14.3). The function resize copies every element and counts the copies, so that the experiments can report them.
$ gcc -std=c17 -O2 -Wall -Wextra -o vec_demo vec_demo.c vec.c -lm && ./vec_demo
push 1: size 1 capacity 1 copies so far 0
push 2: size 2 capacity 2 copies so far 1
push 3: size 3 capacity 4 copies so far 3
push 4: size 4 capacity 4 copies so far 3
push 7: size 7 capacity 8 copies so far 7
push 8: size 8 capacity 8 copies so far 7
push 9: size 9 capacity 16 copies so far 15
push 15: size 15 capacity 16 copies so far 15
push 16: size 16 capacity 16 copies so far 15
push 17: size 17 capacity 32 copies so far 31
sum of the elements: 153
pop 9: size 8 capacity 16 copies so far 39
pop 5: size 4 capacity 8 copies so far 43
pop 3: size 2 capacity 4 copies so far 45
pop 2: size 1 capacity 2 copies so far 46
pop 1: size 0 capacity 1 copies so far 46
14.3 Amortised cost
A push usually costs one write; the push that finds the array full costs one write plus as many copies as there are elements. The worst case of one push is therefore , which is true and misleading: such pushes are rare.
Definition 14.5 (Amortised cost)
Operations on a data structure have amortised cost if every sequence of operations, starting from the empty structure, costs at most in total. The bound concerns the worst sequence, not an average over inputs: no probability is involved.
Definition 14.6 (Aggregate, accounting and potential methods)
Three methods prove amortised bounds. The aggregate method bounds the total cost of any sequence directly. The accounting method charges each operation a fixed number of credits, spends one credit per unit of actual cost, and shows that the credits stored never become negative. The potential method chooses a potential function from the states of the structure to the reals, and calls the amortised cost of the -th operation, of actual cost ; if after every sequence, the total actual cost is at most the total amortised cost.
The last claim is a telescoping sum: .
Proposition 14.7 (Pushes on the doubling array)
Starting from an empty array of capacity 1, pushes make fewer than copies, and cost fewer than writes and copies in all: a push has amortised cost 3.
Proof. Aggregate: the copies happen when the size reaches with , and copy that many elements: . With the writes, the total is below .
Accounting: charge 3 credits per push. One pays its write; two are stored with the new element. When an array of capacity fills up, the elements pushed since the last resize have stored credits, which pay for the copies. The store never goes negative.
Potential: let , which is for the empty array and at least 0 after any push. A push without resize costs 1 and raises by 2: amortised 3. A push on a full array of size costs , and goes from to : amortised . ∎
The same analysis applies to any growth factor , with copies per push in place of 2 (Exercise 14.10); but not to a growth by a constant number of cells, which makes the copies quadratic. C++’s std::vector specifies push_back as amortised constant time, which rules out a constant increment.
$ gcc -std=c17 -O2 -Wall -Wextra -o copies copies.c -lm && ./copies
n x1.5: copies, per push x2: copies, per push +16: copies, per push
1000 2104 2.10 1023 1.02 31311 31.31
10000 24239 2.42 16383 1.64 3120625 312.06
100000 276464 2.76 131071 1.31 312456250 3124.56
1000000 2099686 2.10 1048575 1.05 31249562500 31249.56
$ gcc -std=c17 -O2 -Wall -Wextra -o timing timing.c -lm && ./timing
n x1.5 x2 +16 (ns per push)
4096 0.54 0.41 5.58
16384 0.49 0.38 34.08
65536 2.69 0.31 149.83
262144 2.70 0.37 817.84
Copies per push oscillate with (they depend on where falls between two resizes) but stay below 2 for doubling and below 3 for the factor 1.5, as the bound says; with 16 more cells each time, they grow like . The times agree: doubling costs under half a nanosecond per push and the factor 1.5 from half a nanosecond to under three, while the increment costs four to six times more at each fourfold increase of , as copies growing like predict.
The binary counter is the second classic example. A counter of bits is incremented by turning its trailing 1s into 0s and the next 0 into a 1. An increment can flip all bits, but bit 0 flips at every increment, bit 1 at every second, bit at every -th: increments make fewer than flips (Exercises 14.8 and 14.9).
static int increment(int bits[K]) { // returns the number of bits flipped
int i = 0;
while (i < K && bits[i] == 1) bits[i++] = 0; // the trailing 1s become 0
if (i < K) bits[i] = 1; // and the next 0 becomes 1
return i < K ? i + 1 : i;
}
$ gcc -std=c17 -O2 -Wall -Wextra -o counter counter.c -lm && ./counter
n flips per incr.
8 15 1.8750
64 127 1.9844
512 1023 1.9980
4096 8191 1.9998
32768 65535 2.0000
Shrinking
An array that only grows wastes memory after many pops. Halving the capacity when the array is half full looks symmetric with doubling, and is a trap: at a size just above a power of 2, a push doubles the capacity, a pop halves it, and each copies every element. Shrinking at a quarter leaves room in both directions after each resize.
$ gcc -std=c17 -O2 -Wall -Wextra -o thrash thrash.c -lm && ./thrash
shrink at 1/2: 1000 operations after the fill, 1024000 copies, 1024.0 each
shrink at 1/4: 1000 operations after the fill, 1024 copies, 1.0 each
14.4 The circular buffer
A queue takes elements at the front and adds them at the back. In an array, taking the front would shift every element, or leave the used part drifting to the right; a circular buffer lets it wrap around.
Definition 14.8 (Circular buffer)
A circular buffer stores a queue in an array of capacity with a head index and a count : the queue is . Taking the front advances modulo ; adding at the back writes .
void ring_put(ring *r, int x) {
if (r->count == r->capacity) { // full: copy in queue order into twice the room
int *data = checked(calloc(2 * r->capacity, sizeof(int)));
for (size_t i = 0; i < r->count; i++)
data[i] = r->data[(r->head + i) % r->capacity];
free(r->data);
*r = (ring){data, 0, r->count, 2 * r->capacity};
}
r->data[(r->head + r->count) % r->capacity] = x;
r->count++;
}
int ring_take(ring *r) {
int x = r->data[r->head];
r->head = (r->head + 1) % r->capacity;
r->count--;
return x;
}
$ gcc -std=c17 -O2 -Wall -Wextra -o ring_demo ring_demo.c ring.c -lm && ./ring_demo
put 1..4 [ 1] 2 3 4 . size 4
take 1, 2 . . [ 3] 4 . size 2
put 5, 6 6 . [ 3] 4 5 size 4
put 7 6 7 [ 3] 4 5 size 5
put 8 (grow) [ 3] 4 5 6 7 8 . . . . size 6
Keeping the count rather than a second index matters: with a head and a tail index only, the full and the empty buffer both have (Exercise 14.5). Growth copies the elements in queue order, from the head, not in the order of the cells: copying the cells as they are would break the wrap-around.
In practice
Python’s list and C++’s std::vector are dynamic arrays. Python’s collections.deque is a chain of fixed-size blocks, and the buffers between a producer and a consumer, from keyboard input to network cards, are queues in fixed blocks with wrapping indices. A program that knows how many elements it will push can reserve the capacity once and avoid every copy.
14.5 Exercises
Exercise 14.1 ★
Predict the three lines this program prints, with the doubling array of Listing 14.2.
int main(void) {
vec *v = vec_new();
for (int i = 0; i < 6; i++) vec_push(v, i);
printf("%zu %zu\n", vec_size(v), vec_capacity(v));
for (int i = 0; i < 4; i++) vec_pop(v);
printf("%zu %zu\n", vec_size(v), vec_capacity(v));
vec_push(v, 9);
vec_push(v, 9);
vec_push(v, 9);
printf("%zu %zu %ld\n", vec_size(v), vec_capacity(v), vec_copies(v));
vec_free(v);
return 0;
}
Solution
Solution of Exercise 14.1.
6 8
2 4
5 8 13
Six pushes leave size 6 in capacity 8, after copies . The pops bring the size to 5, 4, 3, 2; at 2, , and the capacity halves to 4 with 2 copies. Three pushes: sizes 3 and 4 fit, the fifth element doubles the capacity to 8 with 4 copies: .
Exercise 14.2 ★
How many element copies do 10 pushes make on the doubling array, starting from capacity 1? And 10 pushes when each resize adds 2 cells?
Solution
Solution of Exercise 14.2.
Doubling: resizes at pushes 2, 3, 5 and 9, copying elements. Adding 2 cells: capacities 1, 3, 5, 7, 9, 11, with resizes when the size is 1, 3, 5, 7 and 9: copies, already more, and growing quadratically.
Exercise 14.3 ★
A circular buffer of capacity 4 starts empty. Draw its cells, head and count after: put 1, put 2, put 3, take, take, put 4, put 5, put 6, take.
Solution
Solution of Exercise 14.3.
After three puts: [1 2 3 .], , . After two takes: , (the queue is 3). Put 4 goes to cell 3, put 5 to cell , put 6 to cell 1: [5 6 3 4], , , full. The last take returns 3: , , the queue is 4, 5, 6.
Exercise 14.4 ★
How many bits do 8 increments flip, starting from 0? List the flips of each increment.
Solution
Solution of Exercise 14.4.
The increments from 0 to 8 flip 1, 2, 1, 3, 1, 2, 1 and 4 bits: 15 in all, .
Exercise 14.5 ★★
This buffer keeps a head and a tail index. Explain the output, and give two ways to repair it.
enum { N = 4 };
int data[N];
int head = 0, tail = 0; // the queue is data[head..tail), modulo N
int empty(void) { return head == tail; }
void put(int x) { data[tail] = x; tail = (tail + 1) % N; }
int take(void) { int x = data[head]; head = (head + 1) % N; return x; }
int main(void) {
for (int x = 1; x <= 4; x++) put(x);
printf("after four puts, empty() says %d\n", empty());
int n = 0;
while (!empty()) n++, take();
printf("taken: %d elements\n", n);
return 0;
}
after four puts, empty() says 1
taken: 0 elements
Solution
Solution of Exercise 14.5.
After four puts in four cells, tail has wrapped to 0, equal to head: the full buffer looks empty, and the loop takes nothing. With two indices modulo there are only possible differences tail - head for possible sizes, 0 to . Two repairs: keep the count (as Listing 14.4 does), or never fill the last cell, declaring the buffer full when (tail + 1) % N == head, at the price of one unused cell.
Exercise 14.6 ★★
In Output 14.6, explain the 1024 copies per operation of the half policy, and the one copy per operation of the quarter policy. Give a sequence of operations that costs copies under the half policy.
Solution
Solution of Exercise 14.6.
Half policy: at size 1024 in capacity 1024, a push doubles (1024 copies) to size 1025 in 2048; the pop brings the size to , and the capacity halves (1024 copies). Every operation copies 1024 elements. Quarter policy: the first push copies 1024; then the size moves between 1024 and 1025 in capacity 2048, far from both 2048 and 512: no other copy, so per operation. For : pushes, then alternating operations of copies each.
Exercise 14.7 ★★
Write an abstract type “stack of int” (stack.h, stack.c) on top of vec.h, with a constructor, two accessors (stack_empty, stack_top) and two transformers, and test it, including on a bracket checker.
Solution
Solution of Exercise 14.7.
struct stack {
vec *items; // the top is the last element
};
stack *stack_new(void) {
stack *s = malloc(sizeof *s);
if (s == NULL) exit(1);
s->items = vec_new();
return s;
}
void stack_free(stack *s) {
vec_free(s->items);
free(s);
}
bool stack_empty(const stack *s) { return vec_size(s->items) == 0; }
int stack_top(const stack *s) { return vec_get(s->items, vec_size(s->items) - 1); }
void stack_push(stack *s, int x) { vec_push(s->items, x); }
int stack_pop(stack *s) { return vec_pop(s->items); }
The header exercises/stack.h declares the six operations with typedef struct stack stack;. The top is the last element of the array, so push and pop are those of the array, with amortised cost . The test pushes and pops 1000 values and checks brackets: ([()[]]) is balanced, ([)] and (( are not.
Exercise 14.8 ★★
By the aggregate method, prove that increments of a binary counter, from 0, flip fewer than bits.
Solution
Solution of Exercise 14.8.
Bit changes at the increment from to exactly when divides , which happens times for . The total is .
Exercise 14.9 ★★
Prove the same bound by the accounting method: how many credits per increment, and where are they stored?
Solution
Solution of Exercise 14.9.
Charge 2 credits per increment. An increment sets exactly one bit from 0 to 1 (unless it overflows): one credit pays that flip, and the other is stored on the bit that is now 1. The flips from 1 to 0 are paid by the credits stored on those bits. Every bit at 1 holds one credit, so the store is never negative, and increments flip at most bits.
Exercise 14.10 ★★★
The array grows by a factor when full (capacity becomes at least , for instance ; the factor 1.5 of the programs gives ). Prove with a potential that pushes make at most about copies, and compare with Output 14.3.
Solution
Solution of Exercise 14.10.
Let for size and capacity . A push without resize copies nothing and raises by . A push on a full array of size copies elements, and, the capacity growing by at least , changes by at most : amortised copies. Right after a resize , so , which is non-negative for ; it stays so as pushes raise it. Hence pushes copy at most plus a constant from and the rounding of the new capacity. For the bound is 3 (the table reaches 2.76), for it is 2 (the table reaches 1.64).
Exercise 14.11 ★★★
With growth and shrinking to half when a quarter full, prove that any sequence of pushes and pops from the empty array makes at most copies. Use when and when , for size and capacity .
Solution
Solution of Exercise 14.11.
always, and for the empty array of capacity 1. Pushes: in the upper half, ; in the lower half, ; on a full array of size , copies and goes from to 2, amortised . Pops without resize: in the upper half, in the lower. A pop that shrinks leaves size in capacity : goes from to , with copies: amortised 1 (the small capacities 4 and 2 give 1 and ). Every amortised cost is at most 2, so operations copy at most , hence at most , an integer. The test checks it along 200 000 random operations.
Exercise 14.12 ★★★
Write a dynamic array of elements of any type: the constructor takes the size of an element in bytes, push copies an element from an address, and gvec_at returns the address of an element. Test it with double and with a structure.
Solution
Solution of Exercise 14.12.
struct gvec {
unsigned char *data;
size_t elem_size, size, capacity;
};
static void resize(gvec *v, size_t capacity) {
unsigned char *data = malloc(capacity * v->elem_size);
if (data == NULL) exit(1);
if (v->size > 0) memcpy(data, v->data, v->size * v->elem_size);
free(v->data);
v->data = data;
v->capacity = capacity;
}
size_t gvec_size(const gvec *v) { return v->size; }
void *gvec_at(gvec *v, size_t i) { return v->data + i * v->elem_size; }
void gvec_push(gvec *v, const void *elem) {
if (v->size == v->capacity) resize(v, 2 * v->capacity);
memcpy(gvec_at(v, v->size++), elem, v->elem_size);
}
void gvec_pop(gvec *v, void *out) {
memcpy(out, gvec_at(v, --v->size), v->elem_size);
if (v->capacity > 1 && v->size <= v->capacity / 4) resize(v, v->capacity / 2);
}
Elements are copied with memcpy, elem_size bytes at a time, and the address of element is the start of the block plus . The user casts it back: *(double *)gvec_at(d, 4000). The test pushes 5000 doubles and pops them back in reverse, then stores three book structures and changes one in place through its address.
14.6 Problem: The binary counter and the elastic array
Problem 14.1
Weekend problem — The binary counter and the elastic array
A program tries every sequence of pushes and pops on the policy of vec.c (double when full, halve when a quarter full), for even up to 26, and prints the largest number of copies with one sequence that makes them.
static long copies_of(long m, long mask) { // bit i of mask: 1 push, 0 pop
long size = 0, capacity = 1, copies = 0;
for (long i = 0; i < m; i++) {
if (mask >> i & 1) {
if (size == capacity) {
copies += size;
capacity *= 2;
}
size++;
} else {
if (size == 0) return -1; // a pop on the empty array: not allowed
size--;
if (capacity > 1 && size <= capacity / 4) {
copies += size;
capacity /= 2;
}
}
}
return copies;
}
$ gcc -std=c17 -O2 -Wall -Wextra -o elastic elastic.c -lm && ./elastic
m copies copies/m a worst sequence (+ push, - pop)
2 1 0.500 ++
4 3 0.750 +++-
6 7 1.167 +++++-
8 9 1.125 +++++---
10 15 1.500 +++++++++-
12 15 1.250 +++++++++---
14 19 1.357 +++++++++-----
16 21 1.312 +++++++++-------
18 31 1.722 +++++++++++++++++-
20 31 1.550 +++++++++++++++++---
22 34 1.545 +++--++++++++++++++++-
24 37 1.542 +++++---+++++++++++++++-
26 40 1.538 +++++----++++++++++++++++-
from 2^15 - 1, 1000 increments and decrements alternating: 16000 flips, 16.0 each
Part I — The counter.
- Show that an increment from flips bits, where is the number of trailing 1s of (when ).
- How many of the integers have exactly trailing 1s?
- Show that bit flips exactly times in increments from 0.
- Deduce that the total is , and that it equals when is a power of 2.
- Check the table of Output 14.5.
- What is the worst case of a single increment, and why does it not contradict the amortised bound?
Part II — The doubling array, three ways.
- Count exactly the copies made by pushes from capacity 1, as a function of .
- Write the accounting argument for pushes with 3 credits each, and say why 2 credits would not do.
- Check that is at least 0 after every push.
- Give the amortised cost of each push of Output 14.2 with this .
- With pushes, what is the largest capacity, and so the largest unused memory, as a fraction of the size?
- Which of the three methods would you use to explain the result to a colleague, and why?
Part III — Shrinking.
- With shrinking at a half, describe the state after filling to elements, then one push, then one pop.
- Deduce that alternating operations after the fill cost copies.
- With shrinking at a quarter, show that after any resize the size is exactly half the new capacity.
- Deduce that between two resizes at least a quarter of the capacity’s worth of operations happen.
- Read the table of Output 14.9: which sequences are the worst, and what is the largest ratio of copies to operations?
- Show that pushes make copies, so that the ratio approaches 2.
Part IV — A decrement breaks the bound.
- Write the decrement of the counter, and give the flips of a decrement from .
- From , alternate increment and decrement: how many flips per operation? Check with Output 14.10.
- Deduce that operations among increments and decrements can cost flips when the counter has bits.
- With digits , 0 and 1 in base 2 (each number then has several representations), an increment and a decrement can each be made to change a bounded number of digits in the amortised sense. Why does this not contradict the previous question?
- Is the amortised bound of the array, copies, still valid for any mix of pushes and pops? Why do pops not break it as decrements break the counter’s?
- State the named result of the problem, the elastic array theorem: the constant with at most copies for any operations, why it is the smallest, and the worst ratios found by the program.
Solution
Solution of Problem 14.1.
1. The trailing 1s become 0 and the next bit, a 0, becomes 1: flips.
2. Bits 0 to are 1, bit is 0, the others are free: integers.
3. Bit flips from to exactly when divides : times.
4. ; for the sum is .
5. 15, 127, 1023, 8191 and 65 535 flips for : each is .
6. From , all bits flip. Such increments are rare: one in from 0.
7. : the resizes copy with . For , 31.
8. A push pays its write and stores two credits on its element. When capacity fills, the elements pushed since the last resize hold credits, one per copy. With 2 credits, only would be stored.
9. After a push the array holds more than half its capacity: either no resize happened and the size grew, or a resize left size in capacity . So .
10. 3 for each of the seventeen pushes, as the dashed line of the figure shows.
11. The capacity is : the unused cells are fewer than the elements, nearly as many right after a resize.
12. The accounting method: credits stored on elements show where the cost of a copy comes from.
13. Size in capacity ; the push copies elements into capacity ; the pop leaves size , half of it, and copies elements back into capacity . The state is the same as after the fill.
14. Each operation then copies elements: copies.
15. A growth copies elements into capacity ; a shrink copies elements into capacity . Either way the copied elements fill exactly half the new capacity .
16. The next growth needs more pushes, the next shrink at least pops; a resize copies at most elements, so the copies are paid by at least operations: a first, crude bound of 4 per operation.
17. The worst sequences push up to just past a power of 2, sometimes after a shrink and a regrowth (+++--+++…). The largest ratio is , at : seventeen pushes and one pop.
18. The resizes copy elements, and .
19. The trailing 0s become 1 and the next 1 becomes 0. From : flips.
20. 16 per operation: from (fifteen 1s), the increment flips 16 bits to reach , the decrement flips them back. The output shows 16 000 flips for 1000 operations.
21. Each operation flips bits when the counter alternates between and with : in all.
22. Question 21 is about the standard representation, which is unique: and differ in bits, so any method that stores them must flip them. A redundant representation does not store either, but some equivalent form of each, which leaves room to absorb a carry later.
23. Yes: the potential of Exercise 14.11 covers any mix. The quarter rule leaves slack in both directions after each resize; the binary counter has no slack between and .
24. The elastic array theorem: with growth and shrinking to half when a quarter full, any pushes and pops from the empty array make at most element copies (Exercise 14.11). The constant 2 is the smallest possible: pushes make copies, a ratio that approaches 2. The exhaustive search finds at most 1.722 copies per operation for , at seventeen pushes and a pop.