Vectors Lists Sequences Skip Lists
Vectors Lists Sequences Skip Lists
0 N-1
V
0 1 2 r n
Array based Vector: Insertion
• In operation insert(r,e) we need to make
room for the new element by shifting forward
the n r elements V[r], …, V[n 1]
• In the worst case (r 0), this takes O(n) time
V
0 1 2 r n
V
0 1 2 r n
V o
0 1 2 r n
Deletion
• In operation erase(r) we need to fill the hole left
by the removed element by shifting backward the n
r 1 elements V[r 1], …, V[n 1]
• In the worst case (r 0), this takes O(n) time
V o
0 1 2 r n
V
0 1 2 r n
V
0 1 2 r n
Insertion and Deletion Code
Performance
• In the array based implementation of a Vector
– The space used by the data structure is O(n)
– size(), empty(), at(r) and set(i,e) run in O(1) time
– insert(i,e) and erase(i) run in O(n) time
• If we use the array in a circular fashion, insert(i,e)
and erase(i) run in O(1) time
• In an insert(i,e) operation, when the array is full,
instead of throwing an exception, we can replace
the array with a larger one
Performance
Exercise:
• Implement the Deque ADT using Vector functions
– Deque functions:
• first(), last(), insertFirst(e), insertLast(e), removeFirst(),
removeLast(), size(), isEmpty()
– Vector functions:
• at(i), set(i,e), insert(i,e), erase(i), size(), empty()
Exercise Solution:
• Implement the Deque ADT using Vector functions
– Deque functions: first(), last(), insertFirst(e), insertLast(e), removeFirst(), removeLast(), size(), isEmpty()
– Vector functions: elemAtRank( r), replaceAtRank(r,e), insertAtRank(r,e), removeAtRank(r ), size(), isEmpty()
head tail