冒泡排序C - 链接列表

时间:2013-02-26 01:27:25

标签: c bubble-sort

所以这是我的小泡泡排序功能的问题。我可以对值进行排序,但总是在3个节点后得到一个截止值。一个例子是:

对以下内容进行排序:

3 2 54 五 4

我总是得到(从最小的头部):

2 3 4

就是这样,没有别的。

 void sortByLine (struct lnode** head) {
      int count = 1;
  while(count){
      struct lnode *temp =*head;
    count = 0;
    while(temp != NULL){
        struct lnode *next = nodeGetNext(temp);
        if(next != NULL){           
           if((lineCmp(temp,next)) > 0 ){
            swap(head, next,temp);
            count = 1;
           }
        }
        temp = nodeGetNext(temp);
    }
}

}

Line Cmp功能:

int lineCmp (struct lnode* n1, struct lnode* n2) {
  int node1 = nodeGetLine(n1);
  int node2 = nodeGetLine(n2);

  if(node1 == node2){
      return 0;
  }
  else if(node1 > node2){
      return 1;
  }
  else
      return -1;

}

交换功能:

 void swap (struct lnode** head, struct lnode* n1, struct lnode* n2) {
    struct lnode *prevn1 = nodeGetPrev(*head, n1);   
    struct lnode *prevn2 = nodeGetPrev(*head, n2);

  struct lnode *nextn1 = nodeGetNext(n1);
  struct lnode *nextn2 = nodeGetNext(n2);   

  if(prevn2 == n1 && prevn1 == NULL){
      evictNode(head, n2);
      pushNode(head, n2);
  }
  else if(prevn1 == n2 && prevn2 == NULL){
      evictNode(head, n1);
      pushNode(head, n1);
  }
  else if(prevn1 == n2 && nextn1 == NULL){
      evictNode(head, n1);
      insertNode(head, prevn2 , n1);   
  }
  else if(prevn2 == n1 && nextn2 == NULL){
      evictNode(head, n2);
      insertNode(head, prevn1, n2);
  }   
  else{
  evictNode(head, n1);
  evictNode(head, n2);   
  insertNode(head, prevn2 , n1);   
  insertNode(head, prevn1 , n2);
  }

}

1 个答案:

答案 0 :(得分:0)

您的问题出在交换功能中:删除节点可能会使先前计算的节点无效

 void swap (struct lnode** head, struct lnode* n1, struct lnode* n2) {
    struct lnode *prevn1 = nodeGetPrev(*head, n1);   
    struct lnode *prevn2 = nodeGetPrev(*head, n2);

  struct lnode *nextn1 = nodeGetNext(n1);
  struct lnode *nextn2 = nodeGetNext(n2);   

  if(prevn2 == n1 && prevn1 == NULL){
      evictNode(head, n2);
      pushNode(head, n2);
  }
  else if(prevn1 == n2 && prevn2 == NULL){
      evictNode(head, n1);
      pushNode(head, n1);
  }
  else if(prevn1 == n2 && nextn1 == NULL){
      evictNode(head, n1);
      insertNode(head, prevn2 , n1);   
  }
  else if(prevn2 == n1 && nextn2 == NULL){
      evictNode(head, n2);
      insertNode(head, prevn1, n2);
  }   
  else if (n1==prevn2)
  {
       evictNode (head, n1);
       insertNode(head, n2, n1);  
  }
  else if (n2==prevn1)
   {
       evictNode (head, n2);
       insertNode(head, n1, n2);  
   } 
  else {
   evictNode(head, n1);
   evictNode(head, n2);   
   insertNode(head, prevn1, n2);
   insertNode(head, prevn2, n1);
  }
}