gpt4 book ai didi

c - 使用 C 中的 qsort 函数对数据结构排序的问题

转载 作者:太空宇宙 更新时间:2023-11-04 01:13:29 25 4
gpt4 key购买 nike

我需要订购一个数据结构数组,其中包含与节点起点、终点和权重相关的信息。问题是没有正确排序,因为如果两个值等于 array.originNode 简单地采用你得到的第一个值而不是它应该排序的。

这就是我的代码对结构进行排序的方式

0 1 30
1 3 22
2 3 20
3 5 20
3 4 15

Process returned 0 (0x0) execution time : 0.015 s

这是它应该如何排序

0 1 30
1 3 22
2 3 20
3 4 15
3 5 20

我认为问题出在我作为参数传递给 qsort 的函数,它没有进行正确的比较。如何将我的比较函数更改为我的代码正确排序结构数组?

这是我的完整代码

#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <unistd.h>

typedef struct dataNodes{
int originNode;
int destinationNode;
int weight;
struct dataNodes *next;
} ARRAYS;


int function (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}


int main() {
ARRAYS array[6];
int n = 5, i;

array [0].originNode = 3;
array [1].originNode = 3;
array[2].originNode = 1;
array[3].originNode = 0;
array[4].originNode = 2;


array [0].destinationNode = 4 ;
array [1].destinationNode = 5;
array[2].destinationNode = 3;
array[3].destinationNode = 1;
array[4].destinationNode = 3;


array [0].weight = 15;
array [1].weight = 20;
array[2].weight = 22;
array[3].weight = 30;
array[4].weight = 20;


qsort(array,n,sizeof(array[0]),function);
for(i=0; i<n; i++)
{
printf("%d %d %d\n",array[i].originNode,array[i].destinationNode,
array[i].weight);
}
return 0;

}

最佳答案

您需要更改比较函数以正确比较 ARRAY 记录。先比较originNode,如果相同则比较destinationNode。

int function (const void * a, const void * b)
{
const ARRAYS *ap = a;
const ARRAYS *bp = b;
if( ap->originNode < bp->originNode )
return -1;
else if( ap->originNode > bp->originNode )
return 1;
else if( ap->destinationNode < bp->destinationNode )
return -1;
else if( ap->destinationNode > bp->destinationNode )
return 1;
else
return 0;
}

关于c - 使用 C 中的 qsort 函数对数据结构排序的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6659452/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com