Question : Bubble Sorting a Linked List in C

Hello,

I am having trouble with this function to bubble sort a linked list. I am losing nodes. Could you please help me understand what I am doing wrong and get this right?

Thanks
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
void bubble_sort(item *node)
{
   item *first_prev,*first,*second,*temp;
   int i, j, n = 1;
   bool sorted = false;

   //make these 3 pointers point to the head of the list
   temp = node;
   first = node;
   first_prev = node;

 
   //count the number of nodes in the list
   while (first->next != NULL)
   {
      n++;
      first= first->next;
   }


   for (i = 1; i <= n; i++)
   {
      first = temp;
      first_prev = temp;
      second = first->next;

      for (j=1; j<=(n-i); j++)
	  {
         if (first->val > second->val)
         {
             if (first == temp)  
             {
                first->next = second->next;
                second->next = first;
                temp = second;
                first = second;
             }
            else
            {
                first->next = second->next;
                second->next = first;
                first_prev->next = second;
                first = second;
            }
          }
         
          first_prev = first;
          first = first->next;
          second = first->next;
       }               
    }
   sorted = true;

   PrintList();
}

Answer : Bubble Sorting a Linked List in C

>> 70                         root = bubble_sort( root );

Make that :

                        head = bubble_sort(head);

because head is the global pointer that points to the start of the linked list.


>> 304     return first_prev;

Make that :

        return temp;

because that's the pointer that points to the beginning of the sorted list.
Random Solutions  
 
programming4us programming4us