私はnumlists
リンクリストの配列を持っています。リスト内のノードの形式は次のとおりです。ソートされたサブセクションで複数のリンクリストをソートおよびマージする
struct Edge
{
int64_t blocknum;
int64_t location;
struct Edge *next;
};
typedef struct Edge edge;
私は昇順でlocation
によってソートされ、単一リンクリストにすべてのリストをマージする必要があります。各リストはノードが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;
}
この作品を思い付いた機能です。私の質問は次のとおりです:
効率的な並べ替えアルゴリズムの点で私は良くできますか? (ほとんど確かにはい、私はちょうど人々が与えられた前提のソート問題のために思い付くものが不思議です)。
誰かがそれに答える前に、元のバグを見つけたので、私は質問を編集しました。その間に誰かが回答を入力していたら、私に知らせて元に戻します。 – KBriggs