【发布时间】:2022-01-09 06:46:40
【问题描述】:
这是我的合并排序的代码: 这是合并函数
node* Merge(node* h1, node* h2, int &comp, int &swaps){ node *t1 = new node; node *t2 = new node; node *temp = new node;
// Return if the first list is empty.
if(h1 == NULL)
return h2;
// Return if the Second list is empty.
if(h2 == NULL)
return h1;
t1 = h1;
// A loop to traverse the second list, to merge the nodes to h1 in sorted way.
while (h2 != NULL)
{
// Taking head node of second list as t2.
t2 = h2;
// Shifting second list head to the next.
h2 = h2->next;
t2->next = NULL;
// If the data value is lesser than the head of first list add that node at the beginning.
comp++;
if(h1->data > t2->data)
{
t2->next = h1;
h1 = t2;
t1 = h1;
continue;
}
// Traverse the first list.
flag:
if(t1->next == NULL)
{
t1->next = t2;
t1 = t1->next;
}
// Traverse first list until t2->data more than node's data.
else if((t1->next)->data <= t2->data)
{
t1 = t1->next;
goto flag;
}
else
{
// Insert the node as t2->data is lesser than the next node.
temp = t1->next;
t1->next = t2;
t2->next = temp;
}
}
// Return the head of new sorted list.
return h1;
}
这是调用合并函数的合并排序函数。我不知道是否应该将比较和交换计数器放在合并或合并排序中,也不知道将它们放在函数中的哪个位置。
void MergeSort(node **head, int &comp, int &swaps)
{
node *first = new node;
node *second = new node;
node *temp = new node;
first = *head;
temp = *head;
// Return if list have less than two nodes.
if(first == NULL || first->next == NULL)
{
return;
}
else
{
// Break the list into two half as first and second as head of list.
while(first->next != NULL)
{
first = first->next;
if(first->next != NULL)
{
temp = temp->next;
first = first->next;
}
}
second = temp->next;
temp->next = NULL;
first = *head;
}
// Implementing divide and conquer approach.
MergeSort(&first, comp, swaps);
MergeSort(&second, comp, swaps);
// Merge the two part of the list into a sorted one.
*head = Merge(first, second, comp, swaps);
}
我不确定在哪里放置我的交换和比较计数器来计算合并排序进行的交换和比较的数量?
【问题讨论】:
-
我的意思是,在你交换或比较之后,对吧?
-
好吧,mergesort 并没有真正做交换,所以...