双链表的最佳插入排序

时间:2019-03-30 17:00:29

标签: c optimization doubly-linked-list insertion-sort

我正在对双链表(dbl)实施插入排序。双向链表上的新节点的插入以及排序都是实时进行的,而与双向链表的先前状态无关(假设双向链表已被排序)。

下面的指针具有全局范围

head =持有双向链表起始值的指针

tail =持有最后一个值的指针

midl =包含中间值的指针

void insert()
{
    struct node *newnode = getnode(); //This function creates and returns a node 
                                      //The node has integer id along with previous and 
                                      //next pointers
    if (head == NULL)
    {
        head = newnode;
        tail = newnode;    //if no elements in dbl
    } else
    {
        if (newnode->id > tail->id)
        {
            tail->next = newnode;
            newnode->prev = tail; //new element inserted after tail
            tail = tail->next;
        } else if (newnode->id < head->id)
        {
            newnode->next = head;
            head->prev = newnode;
            head = head->prev;         //new element inserted before head
        } else
        {
            struct node *temp;
            if (newnode->id > midl->id)
                temp = tail;
            else
                temp = midl;  //new element inserted in dbl such that sorting is justified
            while (temp != NULL && newnode->id < temp->id)
                temp = temp->prev;
            newnode->prev = temp;
            newnode->next = temp->next;
            temp->next->prev = newnode;
            temp->next = newnode;
        }
    }
}

我的问题:

以上代码段完成了工作。有什么方法可以进一步优化代码以减少插入的比较?

0 个答案:

没有答案