Insertion sort in C using linked list
I have to make a telephone direc开发者_JAVA技巧tory program. The program should read names and numbers from a file. I have successfully created a linked list containing this data. Now I want to sort them alphabetically. How should I do that?
It depends on your objective.
If you want to do this efficiently, stick pointers to every element into an array, and then sort the array alphabetically using an algorithm like quicksort (qsort
in C); lastly, re-create the list from the sorted array.
On the other hand, if this is homework and you have to use insertion sort as the title of the post suggests, it's a different matter.
Sorting linked lists needs an online algorithm (ie an algorithm that doesn't depend on fast random access) like insertion sort or a stack-based mergesort implementation.
If you want to insert (few) items into an already sorted list, use insertion sort. If you want to sort a complete list (or insert a large number of items), use mergesort.
An implementation of these algorithms can be found here:
- ll_sort.h
- ll_sort.c
Please let me know if you find a bug as the code hasn't really been tested.
Insertion sort is slow, but if you want to use it look at http://en.wikipedia.org/wiki/Insertion_sort
There are many other sorting algoritms, the fasted of which (T&C apply) are O(NlogN). I suggest looking at either quicksort or merge sort.
A linked list is just about the worst data structure imaginable for sorting. If you do insertion then you have to do linear traversal across the list. Are you sure you've asked the right question?
Do you want to sort them after you've created the linked list?
The best approach for sorting data like this may be to use a tree and create it sorted as you load the data. A tree data structure is also quick for searching, although a hash would probably be fastest. Note that strcmp is not the quickest way to sort or search. You can maintain an index into the search term and code it so that the index points to the first unmatched character. Then you only need to compare on that one character. However I don't have time to give example code for that.
typedef struct directory_entry_t
{
char *name;
char *number;
directory_entry_t *before;
directory_entry_t *after;
} directory_entry;
...
bool found;
while(!found)
{
int result = strcmp("name", node->name);
if(0 == result)
{
fprintf(stderr, "Duplicate entry for %s.\n", name);
}
else if(0 < result)
{
if(NULL == node->after)
{
/* Create a new node, populate it, and store a pointer to it at node->after. */
found = true;
}
else
{
node = node->after;
}
else
{
/* Like the above case, but for before. */
}
}
void insertionsort(node *head,node *tail)
{
node *temp1=head,*temp2=temp1->next;
node *temp3;
while(temp1->next!=NULL)
{
(temp1==tail)
break;
temp2=temp1->next;
if(temp2->data<temp1->data)
{
int j;
j=temp2->data;
temp2->data=temp1->data;
temp1->data=j;
insertionsort(head,temp2);
}
temp1=temp1->next;
}
}
精彩评论