c - Insertion Sort functions doesn't list all the elements after sorting -


this insertion sort function :

student *sort(student* node)  {      if (node == null || !node->next)         return node;     student *sorted = null;      while (node != null)      {          student  *head = node;          student **tail = &sorted;           node = node->next;          while (!(*tail == null || head->id < (*tail)->id))         {              tail = &(*tail)->next;          }         head->next = *tail;         *tail      = head;     }     return sorted; } 

so if supposed sort 3.3, 3.1 , 3.8 , sorts them such :

3.3 3.8

i don't know happens first element. if give larger set of text sort, misses half of text.

been trying figure out why this. i'm pretty sure it's problem sorting function.

write function. function supposed write sorted result file :

 void write(student* node) {     student * curr = null;    curr = node;   file *ptr = fopen("student_out.txt", "w");   if (curr == null)      {        printf("nothing list. \n");       exit(1);     }    int i=0;   while(curr !=null) {       fprintf(ptr,"%d, %s, %s, %s, %.2f\n", curr->id, curr->firstname,     curr->lastname, curr->major, curr->gpa);       curr = curr -> next;     }  return; } 

seems working, problem print out. example code test case mentioned above, converted c89 compatible (since i'm using visual studio). have swapped names head , node, left them match original example. changed compare stop when (*tail)->id > head->id (using <= in compare instead of <) original order of "equal" nodes preserved.

#include <stdio.h>  typedef struct student_{ struct student_ *next; double id; }student;  student *sort(student* node)  {  student *sorted = null;  student **tail; student *head;     if (node == null || !node->next)         return node;     while (node != null)      {          head = node;          node = node->next;         tail = &sorted;          while (*tail != null && (*tail)->id <= head->id)             tail = &(*tail)->next;          head->next = *tail;         *tail      = head;     }     return sorted; }  int main() { student a[3] = {{&a[1],3.3},{&a[2],3.1},{null,3.8}}; student *b;      b = sort(a);     while(b){         printf("%3.1lf ", b->id);         b = b->next;     }     printf("\n");     return 0; }