【发布时间】:2017-02-14 17:24:06
【问题描述】:
我有一个numlists 链表数组。列表中的节点采用以下形式:
struct Edge
{
int64_t blocknum;
int64_t location;
struct Edge *next;
};
typedef struct Edge edge;
我需要将所有列表合并成一个链表,该链表按location 升序排序。每个列表由节点具有相等blocknum 的块组成,并且这些块中的每一个都已排序。具有较大blocknum 值的列表块的所有位置值都大于具有较小blocknum 的块。子列表中的块已经在本地按blocknum 的顺序排序。这实际上意味着,这归结为按blocknum 升序对块进行排序,我不必太担心location,因为它会自行解决。您可以假设数组的 next 成员有效且已分配,或者显式声明为 NULL。
这是我想出的功能
edge *sort_edges(edge **unsorted, int numlists)
{
edge *sorted_head = NULL;
edge *sorted_current = NULL;
edge *current_edge = NULL;
edge *temp = NULL;
int64_t blocknum;
int i;
int64_t minblock;
int remaining = numlists;
int first = 1;
int minblock_index;
while(remaining) //while there are still more lists to process
{
minblock = LLONG_MAX;
temp = NULL;
minblock_index = INT_MAX;
remaining = numlists;
for (i=0; i<numlists; i++) //loop over the list of head nodes to find the one with the smallest blocknum
{
if (!unsorted[i]) //when a lists is exhausted the lead node becomes NULL, and we decrement the counter
{
remaining--;
}
else //a simple minimum finding algorithm
{
current_edge = unsorted[i];
if (current_edge->blocknum < minblock)
{
temp = current_edge;
minblock = current_edge->blocknum;
minblock_index = i;
}
}
}
if (remaining == 0)
{
break;
}
if (first) //if we have not yet set up the head of the list, we have to save a pointer to the head
{
sorted_head = temp;
sorted_current = sorted_head;
first = 0;
}
else
{
sorted_current->next = temp;
}
blocknum = sorted_current->blocknum;
while (sorted_current->blocknum == blocknum && sorted_current->next) //skip through to the end of the block so that the next section we append will go on the end
{
sorted_current = sorted_current->next;
}
unsorted[minblock_index] = sorted_current->next; //reset the head of the unsorted list to the node after the block
}
return sorted_head;
}
这行得通。我的问题是:
我可以在高效的排序算法方面做得更好吗? (几乎可以肯定,我只是好奇人们在给定假设的情况下会提出什么排序问题)。
【问题讨论】:
-
请注意我编辑了这个问题,因为我在任何人回答之前自己发现了原始错误。如果有人在那段时间输入回复,请告诉我,我会回复它。
标签: c sorting linked-list