我正在尝试使用冒泡排序对单词进行排序,但无法确定错误是什么。我的交换有效,但无法正确排序。
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);
}
}
答案 0 :(得分: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
}