我正在尝试对链接列表进行冒泡排序,但是从第一次开始它就无法工作,但是如果我两次调用该函数,它的排序就会很好,例如,如果列表是:9 8 7 6 5 4 3 2 1 ,排序返回4 3 2 1 5 6 7 8 9!这是怎么了

void sort() {

if(Head == NULL)
    cout << "Sorry but your list is empty! \n";
else {

    int i,j,temp,k = count();
    node *current,*nextNode;

    for(i=0; i<k-1; i++,k--) {
        current = Head;
        nextNode = current->Next;

        for(j = 1; j<k; j++) {
            if(current->item > nextNode->item){
                temp = current->item;
                current->item = nextNode->item;
                nextNode->item = temp;
            }
            current = current->Next;
            nextNode = nextNode->Next;
        }
    }
    cout << "Sorting Succeeded!\n";
}
}

最佳答案

不要增加i。由于j从1开始,因此i应该始终从0开始循环。
更改for(i=0; i<k-1; i++,k--)
for(i=0; i<k-1; k--)

for(i=0; i<k-1; i++,k--)应该运行k-1次。但是,当递增i和递减k时,ik之间的差异以两倍的速率减小,因此它运行k/2次,因此仅k/2个元素在排序。并且当再次运行时,其余的k/2元素也会被排序。

07-24 09:45
查看更多