Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

implement the following c++ function: class sorted_sc_array { public: sorted_sc_

ID: 3727993 • Letter: I

Question

implement the following c++ function:

class sorted_sc_array {

public:

sorted_sc_array() : size_(0), ptr_(nullptr) {

}

~sorted_sc_array() { delete[] ptr_; }

// IMPLEMENT ME

sorted_sc_array(const sorted_sc_array& A){

ptr_ = nullptr;

size_=0;

*this =A;

}

// IMPLEMENT ME

sorted_sc_array& operator=(const sorted_sc_array& A){

if(this != &A){

if(ptr_!=nullptr)

delete[] ptr_;

if(A.size_==0)

ptr_ = nullptr;

else{

ptr_ = new signed char[A.size_];

for(int i =0;i

ptr_[i] = A.ptr_[i];

}

}

size_=A.size_;

  

}

return *this;

}

// RETURNS SIZE OF THE ARRAY (i.e. HOW MANY ELEMENTS IT STORES)

int size() const { return size_; }

// RETURNS RAW POINTER TO THE ACTUAL DATA, CAN BE INVOKED AT ANY TIME

const signed char* data() const { return ptr_; }

// IMPLEMENT ME: AFTER INSERT COMPLETES THE ARRAY MUST BE IN ASCENDING ORDER

void insert(signed char c){

if(size_>capacity){

capacity=capacity*2;

}

signed char* temp = new signed char[capacity];

std::copy(ptr_,ptr_+size_,temp);

temp[size_]=c;

  

if(ptr_!=nullptr){

delete []ptr_;

}

ptr_=temp;

size_++;

std::sort(temp,temp+size_);

}

private:

int size_; // size of the array

signed char* ptr_; // pointer to the array

int capacity=10000;

signed char* temp;

implement the insert function. if prt_'s size >= capacity, create new array pointer temp with the size of capacity *2, and copy all the elements from ptr_ to temp then add the parameter c to temp. increase size.

The main problem I have is the runtime should be o(1). Meaning that only create new array pointer when there are not enough room to store new element. If there are spaces, simpily just add c to the array increase size.

Explanation / Answer

The requirement is that new array should be created only when the
current capacity is full and not everytime we insert.The current
implementation is allocating new array on every insert.So we will modify
that.The modified function is as follows:


void insert(signed char c){
    if(size_>=capacity){
       capacity=capacity*2;
       signed char* temp = new signed char[capacity];
       std::copy(ptr_,ptr_+size_,temp);
       temp[size_]=c;
       if(ptr_!=nullptr){
         delete []ptr_;
       }
       ptr_=temp;
    }
    else {
      ptr[size_] = c;
    }

size_++;
std::sort(ptr,ptr+size_);
}