I´m looking at example 6.7 from http://publications.gbdirect.co.uk/c_book/chapter6/structures.html
(Pasted here for convenience)
struct list_ele *
sortfun( struct list_ele *list )
{
int exchange;
struct list_ele *nextp, *thisp, dummy;
/*
* Algorithm is this:
* Repeatedly scan list.
* If two list items are out of order,
* link them in the other way round.
* Stop if a full pass is made and no
* exchanges are required.
* The whole business is confused by
* working one element behind the
* first one of interest.
* This is because of the simple mechanics of
* linking and unlinking elements.
*/
dummy.pointer = list;
do{
exchange = 0;
thisp = &dummy;
while( (nextp = thisp->pointer)
&& nextp->pointer){
if(nextp->data < nextp->pointer->data){
/* exchange */
exchange = 1;
thisp->pointer = nextp->pointer;
nextp->pointer =
thisp->pointer->pointer;
thisp->pointer->pointer = nextp;
}
thisp = thisp->pointer;
}
}while(exchange);
return(dummy.pointer);
}
I get the basic idea, but I cant really explain whats happening in there. Can someone explain in more depth but in simple manner whats going on in that sort function?
Some questions in general:
- Why is
dummy.pointer = list;needed?dummyis then returned at the end of the function, how come the list is still sorted? - What does the comment
The whole business is confused by working one element behind the first one of interest.mean?
dummyis a local variable that is first set to the start of the list. The temporary variablethispis set to point todummyand so when it is updated, the contents pointed to bydummyare also updated. Thus,dummy.pointerwill eventually point to the element that is the new beginning of the sorted list.listwill still point the original start of the list, so the value is returned so the head pointer can be updated.I think what they mean by confusing is that element we are interested in is
nextp, not the current element (orthisp). That is, we are comparing the next element in the list with the current element, rather than comparing the current one with the previous. I guess that’s confusing, but I don’t really find it so.Note: this is Bubble Sort. A better sort algorithm would be Merge Sort, with an implementation at http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html.