

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
A worksheet on implementing a sorted vector bag using a binary search algorithm in c. It includes a discussion on why storing elements in sorted order is beneficial, an explanation of the binary search algorithm, and an implementation of the add, contains, and remove operations for a sortedvectorbag. The document also compares the use cases of a vectorbag and a sortedvectorbag.
Typology: Exams
1 / 2
This page cannot be seen from the preview
Don't miss anything!


Why would it make sense to store the elements of a Vector in sorted order? To understand, ask yourself the following question. Suppose you were given a telephone book and asked to find the number for an individual named Chris Smith. Now suppose you were asked to find the name of the person who has telephone number 543-7352. Which task is easier? In an earlier class you encountered the binary search algorithm. The version shown below takes as argument the value being tested, and returns in O(log n) steps either the location at which the value is found, or if it is not in the collection the location the value can be inserted and still preserve order. int binarySearch (EleType *data, int size, EleType testValue) { int low = 0; int high = size; while (low < high) { int mid = (low + high) / 2; if (LT(data[mid], testValue)) low = mid + 1; else high = mid; } return low; } To get a feel for the binary search algorithm, try searching for the element 6 in the following array. How many steps does it take? Then try searching for 7. What position is returned? What happens if you perform an insert at that position? Finally, try searching for the values 1 and 16. Again, ask what happens if you perform a search for those elements. 2 4 5 6 8 9 11 15 Using the binary search algorithm, implement a Bag that maintains values in a sorted vector. A Bag, you will remember, implements the three operations add, contains, and remove. Describe the asymptotic execution time for each of the operations. Notice that the VectorBag and the SortedVectorBag implement exactly the same API. Under what circumstances would you want to use a SortedVectorBag instead of a simple VectorBag? VectorBag SortedVectorBag add O(n) contains O(n) remove O(n)
int binarySearch (EleType *data, int size, EleType testValue); void sortedVectorBagAdd (struct vector * v, EleType newValue) { } int sortedVectorBagContains (struct vector *v, EleType testValue) { } void sortedVectorBagRemove (struct vector *v, EleType testValue) { }