Algorithm 标准合并排序算法
我目前正在使用一个相当标准的合并排序文件,但有一些问题。我对数据结构相当陌生,所以我并不完全了解正在发生的事情。任何提示都很好。谢谢 这是密码Algorithm 标准合并排序算法,algorithm,sorting,recursion,merge,mergesort,Algorithm,Sorting,Recursion,Merge,Mergesort,我目前正在使用一个相当标准的合并排序文件,但有一些问题。我对数据结构相当陌生,所以我并不完全了解正在发生的事情。任何提示都很好。谢谢 这是密码 #include <stdio.h> #include <stdlib.h> typedef struct CELL *LIST; struct CELL { int element; LIST next; } LIST merge(LIST list1, LIST list2); LIST split(LIS
#include <stdio.h>
#include <stdlib.h>
typedef struct CELL *LIST;
struct CELL {
int element;
LIST next;
}
LIST merge(LIST list1, LIST list2);
LIST split(LIST list);
LIST MergeSort(LIST list);
LIST MakeList();
void PrintList(LIST list);
int main()
{
LIST list;
list = MakeList();
PrintList(MergeSort(list));
}
LIST MakeList()
{
int x;
LIST pNewCell;
if(scanf("%d", &x) == EOF) return NULL;
else {
pNewCell = (LIST) malloc(sizeof(struct CELL));
pNewCell->next = MakeList();
pNewCell->element = x;
return pNewCell;
}
}
void PrintList(LIST list)
{
while(list != NULL) {
printf("%d\n", list->element);
list = list->next;
}
}
LIST MergeSort(LIST list)
{
LIST SecondList;
if (list == NULL) return NULL;
else if (list->next == NULL) return list;
else {
SecondList = split(list);
return merge(MergeSort(list), MergeSort(SecondList));
}
}
LIST merge(LIST list1, LIST list2)
{
if (list1 == NULL) return list2;
else if(list2 == NULL) return list1;
else if(list1->element <= list2->element){
list1->next = merge(list1->next, list2);
return list1;
}
else {
list2->next = merge(list1, list2->next);
return list2;
}
}
LIST split(LIST list)
{
LIST pSecondCell;
if (list == NULL) return NULL;
else if (list->next == NULL) return NULL;
else {
pSecondCell = list->next;
list->next = pSecondCell->next;
pSecondCell->next = split(pSecondCell->next);
return pSecondCell;
}
}
这是错误的:
typedef struct CELL *LIST;
struct CELL {
int element;
LIST next;
}
请尝试以下方法:
typedef struct CELL {
int element;
struct CELL *next;
} CELL, *LIST;
请注意,next
必须是一个指针,而不是另一个CELL
struct
您的第一条错误消息只是指出您在声明
struct CELL
后遗漏了分号。(这也是为什么merge()
的声明被忽略的原因。)Oh!我错过了分号。听起来不错。谢谢你的帮助!递归合并将占用O(n)堆栈空间,这不是学习的问题,但对于大型列表来说是个问题。如果感兴趣,可以考虑使用相同的MyGe()函数实现一个AN,但是使用指向节点的指针数组来存储临时列表,而不是拆分它们。它比拆分列表快,但将列表移动到数组、对数组进行排序以及从排序后的数组创建新列表的速度更快。
typedef struct CELL {
int element;
struct CELL *next;
} CELL, *LIST;