Below is my insertion sort using linked list code. I have debugged this like no other, but can’t figure out how to make it sort. As it sits right now, it goes in an infinite loop going into the if statement in insert(). What do I need to change?
//Sort function to call insertion sort function
void sortEmps()
{
temp = NULL;
struct EMP* next = top;
while(top != NULL)
{
next = top -> next;
insert(temp);
temp = next;
}
top = temp;
}
//Insertion sort function
void insert(struct EMP *emp)
{
prev = NULL;
current = temp;
while (current != NULL && current->id < emp->id)
{
prev = current;
current = current->next;
}
if (prev == NULL)
{
temp = emp;
}
else
{
emp -> next = prev -> next;
prev -> next = emp;
}
}
Here is my struct and add function. Pretty much the only things that are used before the sort. I am able to initialize a bunch of employees, so they are stored.
typedef struct EMP
{
int id;
char name [MAX];
double salary;
struct EMP* next;
} EMPLOYEE;
int addEmployee(char* name, double salary)
{
struct EMP* emp = createEmployee(name, salary);
emp -> next = top;
top = emp;
numEmps++;
//employees[numEmps++] = emp;
return TRUE;
}
Think what will happen if you trying to insert to existing list and current->id > emp->id (you never go into while loop and your prev == null, so by changing the pointer to the head of list to point to something else and as a result loosing your list somewhere in memory which is not dealocated, you are playing with fire.
btw: it has no relation to your insertion sort
I will not write you here the correct way to write this type of code, you can find enough information on the net.
few suggestion , loose your global pointers , and read how to design a linked list that supports an easy insert and delete from the head ( it probably will say something on one more structure that you should use)