为什么此插入链接列表的排序时间比平时长?

时间:2016-08-08 07:02:15

标签: c sorting insertion-sort

这应该是一个高效的代码,但它需要比正常的插入排序花费更长的时间。我无法确定此插入排序的问题。是否存在实施问题?

// function to sort a singly linked list using insertion sort
    void insertionSort(element_t **head_ref)
{
    // Initialize sorted linked list
    element_t *sorted = NULL;

    // Traverse the given linked list and insert every
    // node to sorted
    element_t *current = *head_ref;
    while (current != NULL)
    {
        // Store next for next iteration
        element_t *next = current->next;

        // insert current in sorted linked list
        sortedInsert(&sorted, current);

        // Update current
        current = next;
    }

    // Update head_ref to point to sorted linked list
    *head_ref = sorted;
}


/* function to insert a new_node in a list. Note that this
  function expects a pointer to head_ref as this can modify the
  head of the input linked list (similar to push())*/
void sortedInsert(element_t** head_ref, element_t* new_node)
{
    element_t* current;
    /* Special case for the head end */
    if (*head_ref == NULL || (*head_ref)->val >= new_node->val)
    {
        new_node->next = *head_ref;
        *head_ref = new_node;
    }
    else
    {
        /* Locate the node before the point of insertion */
        current = *head_ref;
        while (current->next!=NULL &&
               current->next->val < new_node->val)
        {
            current = current->next;
        }
        new_node->next = current->next;




current->next = new_node;
    }
}

0 个答案:

没有答案