这种排序方法如何工作?

时间:2014-01-16 14:16:40

标签: c pointers struct

我正在从“The C Book”学习C语言。我认为这是一本好书,我理解它的大部分内容,比如指针。但我无法理解一下使用链表结构进行排序的例子。

如果我在纸上画画,我会继续得到第二个物体的指针如果被切换则不会调整到第一个。也许我正在以错误的方式思考结构中的这些指针。有人可以解释这个交换非常简短,可能就像我在5,99和1的代码中所做的那样。我想了解这种带链表的排序,因为它对以后似乎非常有用。

这是代码:     #包括     #include

struct list_ele{
    int data;
    struct list_ele *pointer;
}ar[3];

struct list_ele *
sortfun( struct list_ele *list );

int
main(){
    struct list_ele *lp;

    ar[0].data = 5;
    ar[0].pointer = &ar[1];
    ar[1].data = 99;
    ar[1].pointer = &ar[2];
    ar[2].data = 1;
    ar[2].pointer = 0;/* mark end of list */

    /* sort list */
    lp = sortfun(ar);
    /* follow pointers */
    while(lp){
        printf("contents %d\n", lp->data);
        lp = lp->pointer;
    }
    exit(EXIT_SUCCESS);
}

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 = this->pointer->pointer;
                    thisp->pointer = nextp;
                }
            thisp = thisp->pointer;
        }
    }while(exchange);

    return(dummy.pointer);
}

1 个答案:

答案 0 :(得分:1)

这是泡泡排序。它通过不按顺序交换项目来工作,重复直到没有更多的项目乱序。如果没有那么多项是有用的,否则需要一些其他方法。 技巧部分可能是这样的:

                thisp->pointer = nextp->pointer;
                nextp->pointer = this->pointer->pointer;
                thisp->pointer = nextp;

用于交换链表中两个元素的顺序。