Sei sulla pagina 1di 2

Vectors 6/8/2002 2:14 PM

Outline and Reading


The Vector ADT (§2.2.1)
Vectors Array-based implementation (§2.2.1)

6/8/2002 2:14 PM Vectors 1 6/8/2002 2:14 PM Vectors 2

The Vector ADT Applications of Vectors


The Vector ADT Main vector operations:
extends the notion of „ object elemAtRank(integer r):

array by storing a returns the element at rank r Direct applications


without removing it
sequence of arbitrary „ Sorted collection of objects (elementary
„ object replaceAtRank(integer r,
objects object o): replace the element at database)
An element can be rank with o and return the old
accessed, inserted or element Indirect applications
removed by specifying „ insertAtRank(integer r, object o):

its rank (number of insert a new element o to have „ Auxiliary data structure for algorithms
rank r
elements preceding it)
„ object removeAtRank(integer r):
„ Component of other data structures
An exception is removes and returns the element
thrown if an incorrect at rank r
rank is specified (e.g., Additional operations size() and
a negative rank) isEmpty()
6/8/2002 2:14 PM Vectors 3 6/8/2002 2:14 PM Vectors 4

Array-based Vector Insertion


Use an array V of size N In operation insertAtRank(r, o), we need to make
A variable n keeps track of the size of the vector room for the new element by shifting forward the
(number of elements stored) n − r elements V[r], …, V[n − 1]
Operation elemAtRank(r) is implemented in O(1) In the worst case (r = 0), this takes O(n) time
time by returning V[r]
V
0 1 2 r n
V V
0 1 2 r n 0 1 2 r n
V o
0 1 2 r n
6/8/2002 2:14 PM Vectors 5 6/8/2002 2:14 PM Vectors 6

1
Vectors 6/8/2002 2:14 PM

Deletion Performance
In operation removeAtRank(r), we need to fill the In the array based implementation of a Vector
hole left by the removed element by shifting „ The space used by the data structure is O(n)
backward the n − r − 1 elements V[r + 1], …, V[n − 1]
„ size, isEmpty, elemAtRank and replaceAtRank run in
In the worst case (r = 0), this takes O(n) time O(1) time
„ insertAtRank and removeAtRank run in O(n) time
V o If we use the array in a circular fashion,
0 1 2 r n
insertAtRank(0) and removeAtRank(0) run in
V O(1) time
0 1 2 r n In an insertAtRank operation, when the array
V is full, instead of throwing an exception, we
0 1 2 r n can replace the array with a larger one
6/8/2002 2:14 PM Vectors 7 6/8/2002 2:14 PM Vectors 8

Potrebbero piacerti anche