Can anybody tell me what's wrong with my selection sort of linked lists? It's meant to sort the whole node, not the data.
#include <iostream>
#include <iomanip>
using namespace std;
typedef struct node
{
int DATA;
node *NEXT;
};
node *HEAD = NULL;
void Create(int data);
void Display();
void Sort();
int main()
{
int num, numOfEl;
cout << "Enter number of elements: ";
cin >> numOfEl;
cout << "Enter " << numOfEl << " numbers: ";
for(int i = 0 ; i < numOfEl ; i++)
{
cin >> num;
Create(num);
}
cout << "\nDisplay before sorting.\n";
Display();
Sort();
cout << "\nDisplay after sorting.\n";
Display();
}
void Sort()
{
node *before_i = NULL; node *i = HEAD;
while(i->NEXT != NULL)
{
node *min = i;
node *before_min = NULL;
node *j = i;
while(j->NEXT != NULL)
{
if(j->NEXT->DATA < min->DATA)
{
before_min = j;
min = j->NEXT;
}
j = j->NEXT;
}
if( before_min != NULL )
{
if( i == before_min )
{
if( i == HEAD )
{
HEAD = min;
if(min->NEXT != NULL)
i->NEXT = min->NEXT;
else
i->NEXT = NULL;
min->NEXT = i;
}
else
{
before_i->NEXT = min;
min = i->NEXT;
i->NEXT = min->NEXT;
min->NEXT = i;
i = min;
}
}
else
{
if( i == HEAD )
{
if(min->NEXT != NULL)
before_min->NEXT = min->NEXT;
else
before_min->NEXT = NULL;
HEAD = min;
min->NEXT = i;
}
else
{
if(min->NEXT != NULL)
before_min->NEXT = min->NEXT;
else
before_min->NEXT = NULL;
before_i->NEXT = min;
min->NEXT = i->NEXT;
}
}
}
before_i = i;
if(i->NEXT != NULL)
i = i->NEXT;
}
}
void Display()
{
node *current;
current = HEAD;
cout << setw(20) << "LAST" << setw(20) << "NUMBER" << setw(20) << "NEXT" << endl;
while(current != NULL)
{
cout << setw(20) << current << setw(20) << current->DATA << setw(20) << current->NEXT << endl;
current = current->NEXT;
}
system("pause>0");
}
void Create(int data)
{
node *front, *tail;
tail = new node;
tail->DATA = data;
tail->NEXT = NULL;
if(HEAD == NULL)
HEAD = tail;
else
{
front = HEAD;
while(front->NEXT!=NULL)
front = front->NEXT;
front->NEXT = tail;
}
}