I have some problems sorting elements on C++. Unluckily, I cannot use C++ containers (professor's request) so I created a new container called 'vettore' whose structure is conceptually similar to a list. So I was trying to sort the ints contained in a 'vettore' structure, but with the following code, giving as input 100, 10, 1 I receive 1, 100, 100. I'm really not getting why it is not working. This is the method of class "vettore" which should sort the elements:
void ordina(){
vettore<T>*aux=this;
vettore<T>*punt_a_min=aux;
bool sentinella=0;
T min=aux->get_my();
while(aux->get_next()!=nullptr){
aux=aux->get_next();
if(aux->get_my()<min){
sentinella=1;
min=aux->get_my();
punt_a_min=aux;
}
}
if(sentinella==1){
punt_a_min->set_obj(this->get_my());
this->set_obj(min);
}
if(this->get_next()!=nullptr)
*(this->get_next()).ordina();
};
And this is the "vettore" class (for what is needed):
template<class T> class vettore{
private:
T my_object; //container
vettore <T> * next; //puntatore al prossimo elemento della lista
public:
vettore():next(nullptr){}; //default constructor
vettore(T oggetto, vettore <T> * successivo=nullptr):next(successivo),my_object(oggetto){}; //faccio puntare la lista a quell'elemento
vettore(const vettore <T> &x):next(x.next),my_object(x.my_object){}; //copy constructor
~vettore(){//destructor
if(next!=nullptr){
delete next;
next=nullptr;
}
};
vettore <T> * get_next(){
return next;
};
T get_my(){
return my_object;
};
T& get_obj(){ //ottenere l'oggetto by reference
return my_object;
};
void ordina(){
//vettore<T>*new_this=this;
vettore<T>*aux=this;
vettore<T>*punt_a_min=aux;
bool sentinella=0;
T min=aux->get_my();
while(aux->get_next()!=nullptr){
aux=aux->get_next();
if(aux->get_my()<min){
sentinella=1;
min=aux->get_my();
punt_a_min=aux;
}
}
if(sentinella==1){
punt_a_min->set_obj(this->get_my());
this->set_obj(min);
}
if(this->get_next()!=nullptr)
*(this->get_next()).ordina();
};
void set_next(vettore<T>*e){
next=e;
}
void set_obj(T obj){
my_object=obj;
};
};
And if this is not correct (or just for curiosity), is there a sort function for a dynamic arrays declared as int * a = new int [n]
?
Thank you very much.