// ----------------------------------------------------------------------------- // DataPack class: an array plus its management information. // Implementation file for all DataPack programs. datapack.cpp // Created by Alice Fischer on Mon August 23, 2009 // ----------------------------------------------------------------------------- #include "datapack.hpp" // --------------------------------------------------------------------- // Doubles the allocation size of the DataPack. void DataPack::grow() { max *= 2; BT* newStore = new BT[max]; for (int k = 0; k < n; ++k) newStore[k] = store[k]; delete[] store; store = newStore; } // --------------------------------------------------------------------- // Read (from user) name of input file and open it. // Read up to max items from input stream and store in array. void DataPack::readData() { char filename[80]; // For name of input file cout << "Enter name of data file: "; cin.getline(filename, 80); ifstream infile(filename); if (!infile) fatal(" Error: couldn't open input %s\n", filename); BT item; for (;;) { infile >> item; if (!infile.good()) break; // Quit for bad data or for end of file. add(item); // Only good items are inserted } } // --------------------------------------------------------------------- // Print the data from the array. void DataPack::printData(ostream& out) const { for (int k = 0; k < n; ++k) { out << store[k] << "\n"; } } // --------------------------------------------------------------------- // Sort data in the data pack. The < and <= operators must be defined for BT. // void DataPack::sortData() { BT* const end = store + n; // Off-board sentinel. BT* pass; // First unsorted item; begin pass here. BT newcomer; // Data value being inserted. BT* hole; // Array slot containing no data. for (pass = &store[1]; pass < end; ++pass) { // Pick up next item and insert into sorted portion of array. newcomer = *pass; for (hole = pass; hole > store; --hole) { if (*(hole - 1) <= newcomer) break; // Insertion slot is found. *hole = *(hole - 1); // Move item 1 slot rightward. } *hole = newcomer; } }