0

我正在尝试使用冒泡排序对单词进行排序,但无法弄清楚错误是什么。我的交换工作但无法正确排序。

void sortByWord (struct node** head) {
    struct node* temp  = (*head);
    struct node* temp2 = (*head);

    int i;
    int j;
    int counter = 0;
    while(temp != NULL)
    {
        temp = nodeGetNextNode(temp);
        counter++;
    }
    for( i = 1; i<counter; i++)
    {
        temp2=(*head);
        for(j = 1; j<counter-1;j++)
        {
            if(wordCmpare(temp2,nodeGetNextNode(temp2))>0)
            {
                swap(head,temp2,nodeGetNextNode(temp2));
                continue;
            }
        }
        temp2 = nodeGetNextNode(temp2);
    }
}
4

1 回答 1

1

继续内部continue循环。也许您需要添加 goto 或标志。

  for( i = 1; i<counter; i++)
  {
        temp2=(*head);
        for(j = 1; j<counter-1;j++)
        {
            if(wordCmpare(temp2,nodeGetNextNode(temp2))>0)
            {
                swap(head,temp2,nodeGetNextNode(temp2));
                goto endOfLoop;
            }
        }

        temp2 = nodeGetNextNode(temp2); // BTW: This line does nothing useful
endOfLoop:       
        ;
  }

这是标志部分:

  for( i = 1; i<counter; i++)
    {
    temp2=(*head);
    boolean flag = false;
    for(j = 1; j<counter-1;j++)
    {
        if(wordCmpare(temp2,nodeGetNextNode(temp2))>0)
        {
            swap(head,temp2,nodeGetNextNode(temp2));
            flag = true;
            break;
        }
    }
    if (flag) continue;
    temp2 = nodeGetNextNode(temp2); // BTW: This line does nothing useful
}
于 2013-02-25T19:29:20.927 回答