First, please use the code tags. See
http://www.cplusplus.com/articles/jEywvCM9/
What you have:
1 2 3 4 5 6 7 8 9
|
void studentsProc::sortLastName()
{
studentptr sortedStudents = NULL; // unused local variable
for ( studentptr s = students; s!= NULL; s=s->next )
{
insertOrder( s );
}
}
|
This one seems to iterate over the students. Not quite the sort that I did expect.
Is this where the magic happens?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
void studentsProc::insertOrder( studentptr node )
{
studentptr prev1, pos1;
studentptr temp1 = new student;
studentptr sortedStudents = NULL; // <---
bool done = false;
pos1 = NULL;
prev1 = NULL;
temp1->lastName = node->lastName;
temp1->firstName = node->firstName;
temp1->studentID = node->studentID;
temp1->email = node->email;
temp1->gpa = node->gpa;
temp1->next = NULL;
for ( studentptr s = sortedStudents; (s!=NULL) && // <---
(done == false); s=s->next)
{
// code
}
// code
printSortedList(sortedStudents); // Why does this function print anything?
}
|
It seems that there is at least one clear showstopper.
Overall, the logic is not clear. One would expect that foo.sort() reorders the elements of foo.
You seem to create a temporary copy (and leak memory like a cheese crate).
Sorting is (usually) based on two operations:
1.
pred(lhs, rhs)
that returns true, if lhs and rhs are is proper order. The
pred defines the order. Both
std::sort
and
std::list::sort
accept user-defined pred.
2.
swap(lhs, rhs)
. When the elements are not in proper order, then they have to swap places to correct the situation.
On array-like containers one has to use copy/move of the
values in the elements.
That is possible with linked list too, but it is also possible to swap by updating the links, which is cheaper if the values are expensive to copy/move.
There are three cases for list insertion:
1. Prepend. Add to front.
1 2
|
temp.next = head;
head = temp;
|
2. Append. Add after last node:
1 2
|
tail = ... last element ...
tail.next = temp;
|
3. Insert after node x:
1 2
|
temp.next = x.next;
x.next = temp;
|
Your insertion sort would:
original = ... the list ...
sorted = nullptr;
WHILE original has nodes
x = node in original
remove x from original
seek position of x in sorted
insert x to sorted at position
original = sorted |