Hello, I am trying to sort a linked list. Following is my code..
First code is only of the sort function.
Second one is the complete code.
Can anyone please point out the error? The program isn't even giving the desired output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
void list::sort_list()
{
node* temp1 = head;
int size = count_nodes();
for (int i = 0; i < size; i++)
{
node* temp2 = temp1;
while (temp2->pnext != NULL)
{
if (temp2->data < temp2->pnext->data)
swap(temp2->data, temp2->pnext->data);
temp2 = temp2->pnext;
}
temp1 = temp1->pnext;
}
}
void test0( ) {
cout << "Empty list\n";
list obj;
obj.display();
obj.sort_list();
obj.display();
}
void test1( ) {
cout << "1-entry list\n";
list obj;
obj.insert_at_the_end(1);
obj.display();
obj.sort_list();
obj.display();
}
void test2a( ) {
cout << "2-entry list already sorted\n";
list obj;
for ( int i = 1 ; i <= 2 ; i++ ) {
obj.insert_at_the_end(i);
}
obj.display();
obj.sort_list();
obj.display();
}
void test2b( ) {
cout << "2-entry list unsorted\n";
list obj;
for ( int i = 2 ; i >= 1 ; i-- ) {
obj.insert_at_the_end(i);
}
obj.display();
obj.sort_list();
obj.display();
}
int main() {
test0();
test1();
test2a();
test2b();
}
There's no point manually entering 20 numbers if it crashes on an empty list.
Figure out the first trivial case that it barfs on.
Then use the debugger to single-step the code on that failing case, and figure out the code execution path that you didn't expect.
When expectation != reality, you found a bug.
Whether that bug is in your code or between your ears (because you failed to understand the problem), that's for you to decide.