5 Array Based Sequences
5 Array Based Sequences
Algorithms in Python
Michael T. Goodrich/ Roberto
Tamassia/ Michael H. Goldwasser
Adapted by Subhrakanta Panda
Chapter 5
Array-Based Sequences
A
0 1 2 i n
© 2021 Goodrich, Tamassia, Goldwasser Array-Based Sequences 3
Arrays of Characters or
Object References
❑ An array can store primitive elements, such as
characters, giving us a compact array.
A
0 1 2 i n
A
0 1 2 i n
A o
0 1 2 i n
© 2021 Goodrich, Tamassia, Goldwasser Array-Based Sequences 7
Element Removal
❑ In an operation remove(i), we need to fill the hole left by
the removed element by shifting backward the n − i − 1
elements A[i + 1], …, A[n − 1]
❑ In the worst case (i = 0), this takes O(n) time
A o
0 1 2 i n
A
0 1 2 i n
A
0 1 2 i n
© 2021 Goodrich, Tamassia, Goldwasser Array-Based Sequences 8
Performance
❑ In an array based implementation of a
dynamic list:
■ The space used by the data structure is O(n)
■ Indexing the element at I takes O(1) time
■ add and remove run in O(n) time in worst case
❑ In an add operation, when the array is full,
instead of throwing an exception, we can
replace the array with a larger one…