我正在尝试使用函数比较器来实现冒泡排序。
我没有收到任何错误,但没有得到正确的输出。
这是我的比较器函数
int ageComparator( struct student_record_node* node1, struct student_record_node* node2 )
{
struct student_record_node *ptr1;
struct student_record_node *lptr;
ptr1=node1;
lptr=node2->next_;
int a=1;
if (ptr1->record_->student_age_>lptr->record_->student_age_&&ptr1->next_ != NULL)
{
//swap(&ptr1, &ptr1->next_);
return a;
}
return 0;
}
这是我的排序功能:
void sort(struct student_record_node **recordsHead, int (*compare_fcn)(struct student_record_node*, struct student_record_node*))
{
int swapped, i;
struct student_record_node *ptr1;
struct student_record_node *lptr = NULL;
do
{
swapped = 0;
ptr1 = *recordsHead;
while (ptr1->next_ != lptr)
{
if (compare_fcn(ptr1,ptr1)>0)
{
swap(&ptr1, &ptr1->next_);
swapped = 1;
}
ptr1 = ptr1->next_;
}
lptr = ptr1;
}
while (swapped);
}
我的交换功能:
void swap(struct student_record_node** node1, struct student_record_node** node2)
{
student_record_node *tmp;
student_record_node *n1=NULL;
student_record_node *n2=NULL;
n1 = *node1;
n2 = *node2;
*tmp->record_= *n1->record_;
*n1->record_= *n2->record_;
*n2->record_ = *tmp->record_;
}
我的输出: 排序之前...
struct student_record_node:
student first name: Name
student second name: Last Name
student id: 1001421758
student age: 15
struct student_record_node:
student first name: Name
student second name: Last Name
student id: 1001421759
student age: 19
struct student_record_node:
student first name: Name
student second name: Last Name
student id: 1001421756
student age: 20
struct student_record_node:
student first name: Name
student second name: Last Name
student id: 1001421758
student age: 16
struct student_record_node:
student first name: Name
student second name: Last Name
student id: 1001421759
student age: 11
struct student_record_node:
student first name: Name
student second name: Last Name
student id: 1001421756
student age: 22
Sorting by age...
struct student_record_node:
student first name: Name
student second name: Last Name
student id: 1001421759
student age: 11
struct student_record_node:
student first name: Name
student second name: Last Name
student id: 1001421759
student age: 11
struct student_record_node:
student first name: Name
student second name: Last Name
student id: 1001421759
student age: 11
struct student_record_node:
student first name: Name
student second name: Last Name
student id: 1001421759
student age: 11
struct student_record_node:
student first name: Name
student second name: Last Name
student id: 1001421759
student age: 11
struct student_record_node:
student first name: Name
student second name: Last Name
student id: 1001421756
student age: 22
通过排序函数后,除最后一个值之外的所有值都是相同的。
最佳答案
student_record_node *tmp;
...
*tmp->record_= *n1->record_;
tmp
未初始化,因此对 *tmp
的访问是未定义的行为。
关于c - C 中函数比较器的冒泡排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43569233/