【发布时间】:2015-04-27 22:58:24
【问题描述】:
这是我的插入排序函数:
Student *sort(Student* node)
{
if (node == NULL || !node->next)
return node;
Student *sorted = NULL;
while (node != NULL)
{
Student *head = node;
Student **tail = &sorted;
node = node->next;
while (!(*tail == NULL || head->id < (*tail)->id))
{
tail = &(*tail)->next;
}
head->next = *tail;
*tail = head;
}
return sorted;
}
因此,如果这应该对 3.3、3.1 和 3.8 进行排序,它会将它们排序为:
3.3 3.8
我不知道第一个元素会发生什么。如果我给它更大的文本集进行排序,它几乎会漏掉一半的文本。
一直在试图弄清楚它为什么这样做。我很确定这是我的排序功能的问题。
写函数。这个函数应该简单地将排序结果写入文件:
void write(Student* node) {
Student * curr = NULL;
curr = node;
FILE *ptr = fopen("student_out.txt", "w");
if (curr == NULL)
{
printf("Nothing to list. \n");
exit(1);
}
int i=0;
while(curr !=NULL) {
fprintf(ptr,"%d, %s, %s, %s, %.2f\n", curr->id, curr->firstname, curr->lastname, curr->major, curr->gpa);
curr = curr -> next;
}
return;
}
【问题讨论】:
-
注意:风格不一致。 (以及,不太重要的缩进)
-
请向我们展示您的所有代码。您可能认为它在排序中,但很可能在其他地方(例如您的遍历和/或打印代码)。我试过了,但它适用于我尝试过的测试用例。但是我必须弥补
Student结构和测试用例,因为您没有提供这些。如果您仍需要帮助,请发帖 Minimal, Complete, and Verifiable example。 -
在第二个 while 循环之后,您将丢失 head-next ... tail 的跳过部分,
head->next = *tail;BTW:这是插入排序(残缺)。对 LL 进行排序的自然方法是合并排序(需要以某种方式递归) -
@wildplasser - 如果使用自下而上的合并算法,列表(或数组)的合并排序不需要递归。对于列表,自下而上的归并排序将比自上而下的归并排序更快。
标签: c sorting linked-list insertion-sort