【发布时间】:2013-12-15 01:04:48
【问题描述】:
我刚刚开始使用 C 进行编程,需要一些帮助来实现插入排序。
我正在做一个 C 列表插入排序。
这是它的伪代码,我想将其转换为 C
否则
使用循环查找列表中应该在新人之前的最后一项 将新人的“下一个”链接设置为指向此列表项之后的任何内容设置此项的“下一个”链接指向新的人
返回(开始)列表
这是我的伪代码的部分实现
else
{
for (int i =0; i < HOW_MANY; i++)
{
people = people -> next;
if (people -> next == NULL) return people;
} //for
}//else
return pointer;
}
这是我的完整方法:
struct person *insert_sorted (struct person *people, char *name, int age) {
//create a new space for the new person
struct person *pointer = malloc(sizeof(struct person));
// check it succeeded
if(pointer == NULL)
{
printf("The program could not allocate memory ");
exit(-1);
}
// set the data for the new person
strcpy(pointer -> name, name);
pointer -> age = age;
pointer -> next = people;
// if the current list is empty
if (people == NULL)
{
// set the new person's "next" link to point to the current list"
pointer -> next = people;
// return a pointer to the new person
return pointer;
}
else
{
for (int i =0; i < HOW_MANY; i++)
{
people = people -> next;
if (people -> next == NULL) return people;
} //for
}//else
return pointer;
}
如果您需要完整的程序代码,请告诉我。
谢谢!
莎拉 :)
【问题讨论】:
-
不清楚你在问什么。有什么问题?
-
嘿 Paddy,很抱歉不够清楚。我的问题是我不确定如何将我的算法(第一个框)实现为 C 代码。第二个框是我尝试进行插入排序,但它不正确。
标签: c list sorting linked-list insertion-sort