链表排序功能只循环一次

时间:2012-04-02 23:18:54

标签: c sorting linked-list

我有一个单独的链表,我试图按价格从最小到最大排序。这是我到目前为止所拥有的

struct part {
    char* name;
    float price;
    int quantity;
    struct part *next;
};

typedef struct part partType;

partType *sort_price(partType **item) {

    int check = 0;        

    if ( *item == NULL || (*item)->next == NULL ) 
        return *item;
    else {

        partType *temp1 = *item;
        partType *temp2 = (*item)->next;

      do{
        check = 0;
        while ( temp2 != NULL && temp2->next != NULL ){
            if (temp2->price > temp2->next->price){
                temp1->next = temp2->next;
                temp2->next = temp2->next->next;
                temp1->next->next = temp2;
                check = 1;
            }
            temp1 = temp2;
            temp2 = temp2->next;
        }
       }while (check == 1);
    }
    return *item;
}

列表已经填充但是当我调用sort函数时,它只交换满足if语句中条件的前两个节点。我不明白为什么在两个临时指针递增后它不再进行检查。

3 个答案:

答案 0 :(得分:1)

您只实现了Bubble排序的一次迭代。你需要重复,直到有一个不能排序的运行......

请注意,您也有一些错误......第一个元素不受您的算法影响。因此,如果我抓取2->1,我会获得2->1而不是1->2。同样,temp1处的元素也不受影响。

所以如果我继续4->3->2->1

t1= 4 ,t2 = 3, t2->next = 2然后交换t1= 4 ,t2 = 2, t2->next = 3

t1= 2 ,t2 = 3, t2->next = 1然后交换t1= 2 ,t2 = 1, t2->next = 3

结果是

 4->2->1->3

修改
条件很简单。添加变量changeOccured 喜欢

   int changeOccured = 1;
   while( changeOccured){
        changeOccured = 0;
        // one run of bubble
            if (temp2->price > temp2->next->price){
              //add this when the if succeed
              changeOccured = 1;
           }

   }

答案 1 :(得分:0)

您可以使用MergeSort等任何就地排序。

如果你知道密钥空间,你也可以去Counting Sort。好的起点是。here

答案 2 :(得分:0)

如果*item == NULL您的示例会崩溃,那么在检查之前您获得temp2

当然,不可能在一次通过中对列表进行排序,因为没有线性排序算法。

然而,您可以将其拆分并递归排序(合并排序)。这“看起来像”单个列表传递(合并)。