Docsity

Bag Data Type: Implementation and Operations, Papers of Data Structures and Algorithms

Toggle sidebar
bg1
Chapter B: Bags
1
Chapter B: Bags
In the stack and the queue abstractions, the order that elements are placed into the
container is important, because the order elements are removed is related to the order in
which they are inserted. For the Bag, the order of insertion is
completely irrelevant. Elements can be inserted and removed entirely at
random.
By using the name Bag to describe this abstract data type, the intent is
to once again to suggest examples of collection that will be familiar to
the user from their everyday experience. A bag of marbles is a good
mental image. Operations you can do on a bag include inserting a new
value, removing a value, testing to see if a value is held in the
collection, and determining the number of elements in the collection. In
addition, many problems require the ability to loop over the elements in
the container. However, we want to be able to do this without exposing details about how
the collection is organized (for example, whether it uses an array or a linked list). Later in
this chapter we will see how to do this using a concept termed an iterator.
The Bag ADT specification
The traditional definition of the Bag abstraction includes the following operations:
Add (newElement)
Place a value into the bag
Remove (element)
Remove the value
Contains (element)
Return true if element is in collection
Size ()
Return number of values in collection
Iterator ()
Return an iterator used to loop over collection
As with the earlier containers, the names attached to these operations in other
implementations of the ADT need not exactly match those shown here. Some authors
prefer “insert” to “add”, or “test” to “contains”. Similarly, there are differences in the
exact meaning of the operation “remove”. What should be the effect if the element is not
found in the collection? Our implementation will silently do nothing. Other authors prefer
that the collection throw an exception in this situation. Either decision can still
legitimately be termed a bag type of collection.
Applications of Bags
to be written
Bag Implementation Techniques
For a Bag we have a much wider range of possible implementation techniques than we
had for stacks and queues. So many possibilities, in fact, that we cannot easily cover them
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Bag Data Type: Implementation and Operations and more Papers Data Structures and Algorithms in PDF only on Docsity!

Chapter B: Bags

In the stack and the queue abstractions, the order that elements are placed into the container is important, because the order elements are removed is related to the order in which they are inserted. For the Bag, the order of insertion is completely irrelevant. Elements can be inserted and removed entirely at random. By using the name Bag to describe this abstract data type, the intent is to once again to suggest examples of collection that will be familiar to the user from their everyday experience. A bag of marbles is a good mental image. Operations you can do on a bag include inserting a new value, removing a value, testing to see if a value is held in the collection, and determining the number of elements in the collection. In addition, many problems require the ability to loop over the elements in the container. However, we want to be able to do this without exposing details about how the collection is organized (for example, whether it uses an array or a linked list). Later in this chapter we will see how to do this using a concept termed an iterator.

The Bag ADT specification

The traditional definition of the Bag abstraction includes the following operations: Add (newElement) Place a value into the bag Remove (element) Remove the value Contains (element) Return true if element is in collection Size () Return number of values in collection Iterator () Return an iterator used to loop over collection As with the earlier containers, the names attached to these operations in other implementations of the ADT need not exactly match those shown here. Some authors prefer “insert” to “add”, or “test” to “contains”. Similarly, there are differences in the exact meaning of the operation “remove”. What should be the effect if the element is not found in the collection? Our implementation will silently do nothing. Other authors prefer that the collection throw an exception in this situation. Either decision can still legitimately be termed a bag type of collection.

Applications of Bags

to be written

Bag Implementation Techniques

For a Bag we have a much wider range of possible implementation techniques than we had for stacks and queues. So many possibilities, in fact, that we cannot easily cover them

in one chapter. Instead, we will spend the next three chapters looking at various implementation techniques, and their advantages and disadvantages. In this chapter we will begin with our two old friends, the dynamic array and the linked list.

Worksheet B1: Building a Bag using a Dynamic Array

For the Bag abstraction we will start from the simpler dynamic array stack described in Chapter S, and not the more complicated deque variation you implemented in Chapter Q. Recall that the Container maintained two data fields. The first was a reference to an array of objects. The number of positions in this array was termed the capacity of the container. The second value was an integer that represented the number of elements held in the container. This was termed the size of the collection. The size must always be smaller than or equal to the capacity. As new elements are inserted, the size is increased. If the size reaches the capacity, then a new array is created with twice the capacity, and the values are copied from the old array into the new. This process of reallocating the new array is an issue you have already solved back in Chapter S. In fact, the method add can have exactly the same behavior as the method push you wrote for the ArrayStack back in Chapter s. That is, add simply inserts the new element at the end of the array. The contains function is also relatively simple. It simply uses a loop to cycle over the index values, examining each element in turn. If it finds a value that matches the argument, it returns true. If it reaches the end of the collection without finding any value, it returns false. Because we want the container to generalized, we define equality using a macro definition. This is similar to the symbolic constant trick we used to define the type EleType. The macro is defined as follows:

ifndef EQ

define EQ(a, b) (a == b)

endif

The ifndef preprocessor instruction allows the user to provide an alternative definition for the EQ function. If none is provided, the primitive equality operator will be used.

void dyArrayInit (struct dyArray v, int initCap) { v->size = 0; v->data = (EleType ) malloc(initCap * sizeof(EleType)); assert(v->data != 0); v->capacity = initCap; } / the following were written already in Chapter S */ void dyArraySetCapacity(struct dyArray *v, int newCap) { … } void dyArrayAdd (struct dyArray *v, EleType e) { dyArrayPush(d, e); } int dyArraySize (struct dyArray v) { return v->size; } / remove was written earlier, to use removeAt / void dynamicArrayRemove (struct dyArray & dy, EleType test) { int I; for (I = 0; I < dy->count; i++) { if (EQ(test, dy->data[i])) { / found it / dynamicArrayRemoveAt(dy, i); return; } } } / you must write the following */ int dyArrayContains (struct dyArray *v, EleType e) { } void dyArrayRemoveAt (struct dyArray *v, int indx) { }

  1. What should the removeAt method do if the index given as argument is not in range?
  2. What is the algorithmic complexity of the method removeAt?
  3. Given your answer to the previous question, what is the worst-case complexity of the method remove?
  4. What are the algorithmic complexities of the operations add and contains?

Constructing a Bag using a Linked List

To construct a Bag using the idea of a Linked List we will begin with the ListDeque abstraction you developed in Chapter Q. Recall that this implementation used a sentinel at both ends and double links. Because we want to quickly determine the number of elements in the collection, we now include an integer data field named count, similar to the count field in the dynamic array bag. Adding an element is a problem that you have already solved. The new value can be inserted at either the front or the back of the list. Similarly, we will assume that you have the methods addLink and removeLink that you wrote in Chapter Q. Recall that addLink took a link as argument and an element value, and created a new link immediately after the argument value. RemoveLink removed the link given as argument. The only change is that we now assume both these methods update the value of count. The method contains must use a loop to cycle over the chain of links. Each element is tested against the argument, using the equals method. If any are equal, then the Boolean value true is returned. Otherwise, if the loop terminates without finding any matching element, the value False is returned. The remove method uses a similar loop. However, this time, if a matching value is found, then the method removeLink is invoked. The method then terminates, without examining the rest of the collection. Complete the implementation of the ListBag based on these ideas: struct dlink { EleType value; struct dlink * next; struct dlink * prev; };

/* conceptual interface */ Boolean (or int) hasNext ( ); EleType next ( ); void remove ( );

  1. What were the algorithmic complexities of the methods addLink and removeLink that you wrote back in Chapter Q?
  2. Given your answer to the previous question, what are the algorithmic complexities of the three principle Bag operations?

Worksheet B3: Array Bag Iterator

One of the primary design principles for collection classes is encapsulation. The internal details concerning how an implementation works are hidden behind a simple and easy to remember interface. To use a Bag, for example, all you need know is the basic operations are add, collect and remove. The inner workings of the implementation for the bag are effectively hidden. When using collections a common requirement is the need to loop over all the elements in the collection, for example to print them to a window. Once again it is important that this process be performed without any knowledge of how the collection is represented in memory. For this person the conventional solution is to use a mechanism termed an Iterator. Each collection provides a function named iterator that returns an object implementing this interface. The functions next and hasNext are used in combination to write a simple loop that will cycle over the values in the collection. Notice that the iterator loop exposes nothing regarding the structure of the container class. The method remove can be used to delete from the collection the value most recently returned by next. Notice that an iterator is an object that is separate from the collection itself. The iterator is a facilitator object , that provides access to the container values. LinkedListIterator itr; EleType current; … ListIteratorInit (aList, itr); while (ListIteratorHasNext(itr)) { current = ListIteratorNext(itr); … /* do something with current */ }

Your first task is to complete the implementation of the function for the dynamic array iterator. Note that the data field currentIndex is initialized to zero when the iterator is constructed. The functions next and hasNext should manipulate this value to achieve the desired purpose. First write the functions hasNext and next, so that the simple iterator loop will work as expected. Only after you have written the first two should you go on to consider the third function, remove. Think carefully about the method remove. You must ensure that the next element after a remove is not skipped over. We will make the simplifying assumption that calls in hasNext and next are strictly interleaved. That is, you cannot invoke next without first checking that there is a value by calling hasNext. The Java standard library does not make this assumption, and as a consequence their iterators have a more complex implementation than do the ones we will examine. In the standard library an iterator will throw a NoSuchElementException if the call on next cannot produce a value. What will your implementation do in this situation? Complete the implementation of the Dynamic Array Iterator: struct dyArrIterator { struct dynamicArray *dy; int currentIndex; } void DyArrIteratorInit (struct dyArray *dy, struct dyArrIterator *itr) { itr->dy = dy; itr->current Index= 0; } int DyArrIteratorHasNext (struct dyArrIterator *itr) { } EleType DyArrIteratorNext (struct dyArrIterator *itr) { struct dyArrIterator { struct dynamicArray *dy; int currentIndex; } void DyArrIteratorInit (struct dyArray *dy, struct dyArrIterator *itr) { itr->dy = dy; itr->current Index= 0; }

void __removeLink (struct LinkedList *q, struct dlink lnk) { … / you wrote this already in chapter q */ q->size = q->size – 1; } int linkedListIteratorHasNext (struct linkedListIterator *itr) { } EleType linkedListIteratorNext (struct linkedListIterator *itr) { } void linkedListIteratorRemove (struct linkedListIterator *itr) { }

Self Study Questions

Short Exercises

Analysis Exercises

Programming Projects