Lesson contents

Growing arrays

A growing array separates the number of items in use from the space reserved for them. When the space fills up, a larger block can take its place.

Simple example

Two slots hold 6 and 2. Reserve more room, copy the two values, then add 9. Print the three values in order.

Start6 2
Result6 2 9
main.rs
fn main() {
    let old: [i64; 2] = [6, 2];
    let mut larger: [i64; 4] = [0, 0, 0, 0];
    let mut used: i64 = 2;
    let mut i: i64 = 0;
    while i < used {
        larger[(i) as usize] = old[(i) as usize];
        i += 1;
    }
    larger[(used) as usize] = 9;
    used += 1;
    i = 0;
    while i < used {
        println!("{}", larger[(i) as usize]);
        i += 1;
    }
}
Output
6
2
9
Advertisements

Everyday examples

Add a late booking

A sheet has spaces for two bookings, 17 and 28. Booking 39 arrives. How can you keep their order?

Start17 28
Result17 28 39

Copy both bookings to a larger sheet and write 39 after them. Empty spaces on the new sheet are available capacity.

Extend a shopping list

A list has room for four products, but only products 5 and 8 are listed. Add product 2.

Start5 8
Result5 8 2

Use the third slot. There is still one free slot, so nothing needs to be copied.

Grow a photo album

An album page holds two photos. You replace it with a four-slot page when a third photo arrives. Does the fourth photo need another page?

Start1 2 3
Result1 2 3 4

No. It fits in the reserved fourth slot. Paying for the occasional larger copy saves work on later additions.

Cost and limits

With geometric growth, appending costs constant time on average over many appends. An individual resize still copies the existing items.