如何按降序对此链表进行排序?

时间:2014-01-05 10:38:49

标签: c sorting linked-list

我不知道这是否是基本的,但我只知道如何按升序排序。

 system("cls");
    if (headptr != (struct online*)NULL)
{

    currentptr = headptr;
    for(; currentptr->ptrnext != NULL; currentptr = currentptr->ptrnext)
    {
        for(newptr = currentptr->ptrnext; newptr != (struct online*)NULL; newptr = newptr->ptrnext)
        {
            if(currentptr->score > newptr->score)
            {
                int temp = currentptr->score;
                currentptr->score = newptr->score;
                newptr->score = temp;
            }
        }
    }

}

2 个答案:

答案 0 :(得分:1)

更改

if(currentptr->score > newptr->score)

它的补充操作

if(currentptr->score <= newptr->score)

这将颠倒顺序。

答案 1 :(得分:0)

是的,这很容易。只需更改&#39;&gt;&#39;到&#39;&#39;所以它会以其他顺序交换元素。

我没有测试代码,但是如果你的原始代码片段正常工作,那么你必须只做这个:

system("cls");
    if (headptr != (struct online*)NULL)
{

    currentptr = headptr;
    for(; currentptr->ptrnext != NULL; currentptr = currentptr->ptrnext)
    {
        for(newptr = currentptr->ptrnext; newptr != (struct online*)NULL; newptr = newptr->ptrnext)
        {
            if(currentptr->score < newptr->score)
            {
                int temp = currentptr->score;
                currentptr->score = newptr->score;
                newptr->score = temp;
            }
        }
    }    
}

在这里,您可以观看可视化不同排序算法的动画,这可以帮助您更深入地了解冒泡排序的工作方式:

Sorting Algorithms - Visualized