Professional Documents
Culture Documents
Vectors
Outline and Required Reading: Vectors ( 5.1)
Sequence ADT
Sequence
general purpose linear ADT with methods for accessing, inserting, and removing arbitrary elements Examples: Vector, List, Full Sequence
C B A
Stack
A B C
A B C
A B C
Queue
Deque
Sequence
Vector ADT
Vector sequence that supports random access/insertion/removal
of its elements by their rank
Rank
integer that specifies the number of elements, in a given sequence, before the element in question
abstraction of the concept of index in arrays the rank of an element may change whenever the sequence is
A B C
Supporting Methods
(Observers)
Interface
elementAtRank() replaceAtRank()
insertAtRank(i,e)
insertAtRank()
removeAtRank
Vector Exceptions
ArrayIndexOutOfBoundsException InvalidRankException
rank of V = index of A
Drawback
shifting
removal at rank=1
insertion at rank=1
shifting
Space Usage Poor! Poor O(N), where Nn General Note problems with fixed array size
(space may be wasted or may be insufficient)
NOTE: run times of insertFirst() and insertLast() can be reduced to O(1) with circular array . However, the limited-capacity problem still remains.
Deque Method
Deque
Vector Method size() isEmpty() elementAtRank(0) elementAtRank(size()-1) insertAtRank(0,e) insertAtRank (size(), e) removeAtRank(0) removeAtRank(size()-1)
A B C
Vector
A B
step (1)
A B
step (2)
A
step (3)
10
11
12
Accordingly:
13
2st call for insertAtRank(size()) on full array (more costly than previous) 3rd call for insertAtRank(size()) on full array (more costly than previous)
C
(A+C) copy operations
14
Accordingly: ! ! total number of capacity increases: k total number of copy operations: 1 + 2 + 4 + + 2k-1 = = 2k - 1 = =n-1 hence, the total run time of push method over n elements is (i.e. total run time of n calls of push method): n - 1 (n) The amortized (average) time of a push operation is O(1) !
15
An
head
tail
16
} else {
/* scan backward from trailer */ node = trailer.getPrev(); for (int i=0; i < size()-r-1 ; i++) { node = node.getPrev(); };
O(n/2)
} return node;
17
Space Usage Good! Good O(n), where n the actual number of elements in
the vector.
General Note With LLs the cost of shifting is avoided, but a new cost
of walking through the list to find elements by rank is added; overall, LL implementation is worse!
18
19
20
Q.1 (textbook R-5.2) Describe how we could implement a Stack class (interface) using an already existing Vector class? Q.2 (textbook C-5.13) Discuss another possible implementation of the Deque ADT using the Vector ADT, that is different from the one discussed in class. Q.3 (textbook C-5.5) Q.4 (textbook C-5.14)