#include "Numeric_array_1.hpp" #include #include #include #include #include ///////////////// // Constructor // ///////////////// // Construct an empty array with an initial // capacity of CAPACITY_INCREMENT (10). // An empty array is considered sorted. Numeric_array_1::Numeric_array_1(): capacity_ { CAPACITY_INCREMENT }, array_ { new double[CAPACITY_INCREMENT] }, size_ { 0 }, is_sorted_{ true } { // All member variables are initialized in the initializer list. } //////////////////////////////////////////////////////// // Destructor, copy constructor, move constructor, // // assignment operator, and move assignment operator // //////////////////////////////////////////////////////// // Free the dynamically allocated memory. // The destructor is called when the object is destroyed. Numeric_array_1::~Numeric_array_1() { delete[] array_; capacity_ = 0; array_ = nullptr; size_ = 0; is_sorted_ = true; } // Construct a deep copy of another array: // Allocate new memory and copy all the existing entries. Numeric_array_1::Numeric_array_1( Numeric_array_1 const &other ): capacity_ { other.capacity() }, array_ { new double[other.capacity()] }, size_ { other.size() }, is_sorted_{ other.is_sorted() } { for ( std::size_t k{ 0 }; k < size(); ++k ) { array_[k] = other.array_[k]; } } // Move the contents of another array into this array: // Take ownership of its memory and leave the other array empty. Numeric_array_1::Numeric_array_1( Numeric_array_1 &&other ) noexcept: capacity_ { other.capacity() }, array_ { other.array_ }, size_ { other.size() }, is_sorted_{ other.is_sorted() } { other.capacity_ = 0; other.array_ = nullptr; other.size_ = 0; other.is_sorted_ = true; } // Replace this array with a deep copy of another array. // - Reuse the allocated memory if the capacities are equal. Numeric_array_1 &Numeric_array_1::operator=( Numeric_array_1 const &other ) { if ( this == &other ) { return *this; } if ( capacity_ != other.capacity_ ) { double *new_array{ new double[other.capacity_] }; for ( std::size_t k{ 0 }; k < other.size_; ++k ) { new_array[k] = other.array_[k]; } delete[] array_; array_ = new_array; capacity_ = other.capacity_; } else { for ( std::size_t k{ 0 }; k < other.size_; ++k ) { array_[k] = other.array_[k]; } } size_ = other.size_; is_sorted_ = other.is_sorted_; return *this; } // Replace this array by moving another array: // Release the old memory and take ownership of the other's memory. Numeric_array_1 &Numeric_array_1::operator=( Numeric_array_1 &&other ) noexcept { if ( this == &other ) { return *this; } delete[] array_; capacity_ = other.capacity(); array_ = other.array_; size_ = other.size(); is_sorted_ = other.is_sorted(); other.capacity_ = 0; other.array_ = nullptr; other.size_ = 0; other.is_sorted_ = true; return *this; } /////////////////////////////////////////////////////// // Accessors (observers or queries): // // Member functions that return information about // // an object without modifing that object. // /////////////////////////////////////////////////////// // Return the number of elements currently stored in the array. // - This may be less than the allocated capacity. std::size_t Numeric_array_1::size() const noexcept { return size_; } // Return the number of elements that can be stored // without allocating additional memory. std::size_t Numeric_array_1::capacity() const noexcept { return capacity_; } // Return true if the elements are in nondecreasing order. // - An empty array or an array with one element is sorted. bool Numeric_array_1::is_sorted() const noexcept { return is_sorted_; } // Return the value stored at the given index. // - Throw an exception if the index is out of range. double Numeric_array_1::operator[](std::size_t n) const { if ( n >= size() ) { throw std::out_of_range{ "Numeric_array_1 index out of range" }; } return array_[n]; } // Return the index of the first occurrence of the minimum. // - If sorted, the minimum is at index zero. std::size_t Numeric_array_1::min() const { if ( size() == 0 ) { throw std::domain_error{ "You cannot find the minimum of an empty array" }; } // If the array is sorted, // the minimum entry is the first entry if ( is_sorted() ) { return 0; } std::size_t idx{ 0 }; for ( std::size_t k{ 1 }; k < size_; ++k ) { if ( array_[k] < array_[idx] ) { idx = k; } } return idx; } // Return the index of the last occurrence of the maximum. // - If sorted, the maximum is at the final index. std::size_t Numeric_array_1::max() const { if ( size_ == 0 ) { throw std::domain_error{ "You cannot find the maximum of an empty array" }; } // If the array is sorted, // the maximum entry is the last entry if ( is_sorted() ) { return size() - 1; } assert( size() >= 2 ); std::size_t idx{ size() - 1 }; std::size_t k{ size() - 1 }; while ( k > 0 ) { --k; if ( array_[k] > array_[idx] ) { idx = k; } } return idx; } // Calculate the arithmetic mean of the entries. // - Throw an exception if the array is empty. double Numeric_array_1::mean() const { if ( size() == 0 ) { throw std::domain_error{ "You cannot calculate the mean (the average value) of an empty array" }; } double sum{ 0.0 }; for ( std::size_t k{ 0 }; k < size(); ++k ) { sum += array_[k]; } return sum/static_cast( size() ); } // Calculate the population standard deviation of the entries. // - Divide the sum of squared deviations from the mean // by the number of entries. // - Throw an exception if the array is empty. double Numeric_array_1::std_dev() const { if ( size() == 0 ) { throw std::domain_error{ "You cannot calculate the standard deviation of empty array" }; } double average{ mean() }; double sum_squares{ 0.0 }; for ( std::size_t k{ 0 }; k < size(); ++k ) { double difference{ array_[k] - average }; sum_squares += difference*difference; } return std::sqrt( sum_squares/static_cast( size() ) ); } // Calculate the median without modifying the original array. // - If unsorted, make a copy, sort it, and calculate its median. // - Throw an exception if the array is empty. double Numeric_array_1::median() const { if ( size() == 0 ) { throw std::domain_error{ "You cannot determine the median of empty array" }; } // If this array is not sorted, // make a copy, sort it, and find the median of that array if ( !is_sorted() ) { Numeric_array_1 sorted_copy{ *this }; sorted_copy.sort(); return sorted_copy.median(); } std::size_t middle{ size()/2 }; if ( size()%2 == 1 ) { return array_[middle]; } else { // Halving before addition avoids overflow of the sum in some cases. return array_[middle - 1]/2.0 + array_[middle]/2.0; } } // Search for a value using linear or binary search, // depending on whether the array is sorted. // - Return a matching index, or size() if not found. std::size_t Numeric_array_1::find( double x ) const { check_for_inf_or_NaN( x ); // If the array is not sorted, // perform a linear search if ( !is_sorted() ) { for ( std::size_t k{ 0 }; k < size(); ++k ) { if ( array_[k] == x ) { return k; } } return size(); } assert( is_sorted() ); // Perform a binary search on a sorted array std::size_t low{ 0 }; std::size_t high{ size() }; while ( low < high ) { std::size_t middle{ low + (high - low)/2 }; if ( array_[middle] == x ) { return middle; } else if ( array_[middle] < x ) { low = middle + 1; } else { high = middle; } } return size(); } /////////////////////////////////////////////// // Mutators (modifiers): // // - Member functions that will modify or // // change the contents of the object. // /////////////////////////////////////////////// // Append a value to the end of the array: // Update the sorted status and return the index of the new entry. std::size_t Numeric_array_1::append( double x ) { check_for_inf_or_NaN( x ); if ( size() == capacity() ) { increase_capacity(); } // If the appended value is less than the entry at // the end of the array, the array is no longer sorted if ( (size() != 0) && (x < array_[size() - 1]) ) { is_sorted_ = false; } array_[size()] = x; return size_++; } // Insert a value as though the array were sorted. // - Shift larger preceding entries and return the insertion index. std::size_t Numeric_array_1::insert( double x ) { check_for_inf_or_NaN( x ); if ( size() == capacity() ) { increase_capacity(); } std::size_t k{ size() }; while ( (k > 0) && (array_[k - 1] > x) ) { array_[k] = array_[k - 1]; --k; } array_[k] = x; ++size_; // The previous sorted status remains correct. return k; } // Sort the array into non-decreasing order using insertion sort. // - Return the number of inversions removed during sorting. std::size_t Numeric_array_1::sort() noexcept { if ( is_sorted() ) { return 0; } // Count and return the number of inversions: // - A sorted array has zero inversions. // n(n - 1) // - A strictly decreasing array has -------- inversions. // 2 std::size_t inversion_count{ 0 }; for ( std::size_t k{ 1 }; k < size(); ++k ) { double value{ array_[k] }; std::size_t j{ k }; while ( (j > 0) && (array_[j - 1] > value) ) { array_[j] = array_[j - 1]; ++inversion_count; // Each move removes one inversion --j; } array_[j] = value; } is_sorted_ = true; return inversion_count; } ////////////////////////////// // Private helper functions // ////////////////////////////// // Increase the capacity by CAPACITY_INCREMENT (currently 10). // Allocate new memory, copy the entries, and release the old memory. void Numeric_array_1::increase_capacity() { std::size_t new_capacity{ capacity_ + CAPACITY_INCREMENT }; double *new_array{ new double[new_capacity] }; for ( std::size_t k{ 0 }; k < size_; ++k ) { new_array[k] = array_[k]; } delete[] array_; array_ = new_array; capacity_ = new_capacity; } // Check that the given value is finite. // Throw an exception if it is infinity or NaN. void Numeric_array_1::check_for_inf_or_NaN( double x ) { if ( !std::isfinite( x ) ) { throw std::invalid_argument{ "Values must be finite (not +inf, -inf, or NaN)" }; } } //////////////////////////////////// // Global functions and operators // //////////////////////////////////// // Insert the array into an output stream. // - Display the entries in braces, separated by commas. std::ostream &operator<<( std::ostream &out, Numeric_array_1 const &array ) { if ( array.size() == 0 ) { out << "{}"; return out; } out << "{" << array[0]; for ( std::size_t k{ 1 }; k < array.size(); ++k ) { out << ", " << array[k]; } out << "}"; return out; }