11-alt-impl-subtype - Last time: Extended example of an...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Sheet1 Page 1 Last time: Extended example of an ADT: the intset Today: * Implementation flexibility Given this implementation, how many elements of the array must indexOf examine in the *worst case* if there are 10 elements? If there are 90 elements? We say the time for indexOf grows *linearly* with the size of the set. If there are N elements in the set, we have to examine all N of them in the worst case. If we have large sets, and are performing lots of queries, this might be too expensive. Luckily for us, we can replace this implementation with a different one that can be more efficient. The only change we need to make is to the representation---the the abstraction can stay precisely the same. We'll still use an array (of 100 elements) to store the elements of the set, and the will still occupy the first numElts slots, with no duplicates. However, this time, rather than unsorted, we'll keep the elements in sorted order. The constructor and size methods don't need to change at all---all they use is the numElts field. Likewise, query doesn't need to change either---if the index exists in the array's legal bounds, then it's there. However, the others all do need to change. We'll start with the easiest one: remove. Recall its old definition: void IntSet::remove(int v) { int victim = indexOf(v) if (victim != MAXELTS) { elts[victim] = elts[numElts-1] numElts-- } } This moves the last (and largest) element from the end to the middle,
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Sheet1 Page 2 which breaks the new invariant. So, instead of dong a swap, we have to "squish" the array together to cover up the hole. We'll do that by moving the element next to the hole to the left, and this leaves a new hole. We'll keep moving elements until the hole is off the end of the elements. We'll re-use the variable victim as a loop variable, its invariant is that it always points at the hole in
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 04/04/2008 for the course EECS 215 taught by Professor Phillips during the Winter '08 term at University of Michigan.

Page1 / 12

11-alt-impl-subtype - Last time: Extended example of an...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online