Data Structures, Algorithms, & Applications in C++
Chapter 5, Exercise 37
The code is given below and in the file
vectorListWithHalf.h. Test code is
included in vectorListWithHalf.cpp.
template<class T>
class vectorListWithHalf : public vectorList<T>
{
public:
// constructor and destructor
vectorListWithHalf(int initialCapacity = 10)
: vectorList<T> (initialCapacity) {}
void half();
};
template<class T>
void vectorListWithHalf<T>::half()
{// Remove all odd indexed elements.
// move even indexed elements to new spots
int listSize = (int) element->size();
for (int i = 2; i < listSize; i += 2)
(*element)[i/2] = (*element)[i];
// destroy uneeded elements
int newSize = (listSize + 1) / 2;
element->erase(element->begin() + newSize, element->end());
}
The for loop is iterated O(listSize) times.
Each iteration takes O(1) time.
The complexity of the call to the vector method
erase is O(listSize).
Hence, the complexity of the function is O(listSize).