c++ - Implementing selection sort on a singly linked list -


heya i'm trying implement selection sort algorithm on singly linked list , i'm aware there problem in code although linked list includes numbers 7 1 2 6 output after running 7777 . appreciated.

template<class type> void unorderedlinkedlist<type>::selectionsort() { nodetype<type>* loc; nodetype<type>* minindex; nodetype<type>* temp; temp = first; if(temp == null)     cerr<<"cannot sort empty list."<<endl; else     if(temp->link == null)     cerr<<"list has 1 item sorted."<<endl; else  while(temp != null) {     minindex = minlocation(temp, last);     swap(temp, minindex);     temp = temp->link; } }   template<class type> nodetype<type>* unorderedlinkedlist<type>::minlocation(nodetype<type>* first, nodetype<type>* last)  nodetype<type>* minindex; nodetype<type>* other;  minindex = first; other = minindex->link;  while(other != null) {     if(minindex->info > other->info)     {         minindex = other;         other = other->link;     }      else     {         other = other->link;     }  }     return minindex; } 

then swap:

template<class type> void unorderedlinkedlist<type>::swap(nodetype<type>* first, nodetype<type>* second) {      nodetype<type>* temp;      temp->info = first->info;      first->info = second->info;      second->info = temp->info; } 

from swap function:

 nodetype<type>* temp;  temp->info = first->info; 

that clear case of undefined behavior! declare local variable, pointer, without initialization. directly uses uninitialized variable, leading said ub. since use pointers, should happy program didn't crash.

here don't need pointer or node don't swap nodes. need instance of info is, , use that:

sometype temp; temp = first->info; first->info = second->info; second->info = temp; 

Comments

Popular posts from this blog

libGdx unable to find files in android application data directory -

php - Webix Data Loading from Laravel Link -

python - Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>] error -