Tutorial 02/25

ADTs in C

  • C just uses files for ADTS, not modules/namespaces.

  • Our example ADT is the sequence Operations— creates an empty sequence

  • Insert(s,i,e) - inserts e at index i in sequence S

    • Pre: 0<= i<= Size(S)

      • It's Size(S), to allow for unbounded growth

circle-info

A precondition, is a condition that has to be true, for the rest of the function to be valid.

  • Size(S) - # Elements in S

  • remove(s,i) - removes item at index i from S.

    • Pre: 0<= i<= Size(S) - 1

  • index(s,i) - return the i-th element of S

    • Pre: 0<= i<=Size(s)-1

  • Want our sequence to grow as necessary. What Data Structure ?

Implementation options:

  1. Linked List:

    1. Easy to grow

    2. Slow to Index

  2. Array:

    1. Constant-time Indexing

    2. Harder to grow !

Approach: Partially-filled Heap Array

First File

There is a chance that this Abstract ADT can be used improperly. How can we make this data-structure bullet-proof.

What happens when the array is full?

realloc will get a larger chunk of memory.

  • Good case: S->array can be simply be exapnded into neighbouring memory.

    • The memory is not used.

  • Worse case: An entirely new chunk of memory must be allocated, and the old array has to be copied over at O(n) cost.

Leading Questions:

How big should we make the array??

Last updated