Qsort无法正确对内容进行排序,Kruskal算法
我正在尝试使用QSORT
对结构数组进行分类,但是它不能正确地对内容进行排序。 结构节点由启动顶点,结尾顶点以及从顶点“ a”到顶点'b'的成本组成。
我正在编写Kruskal算法输入的代码
#include <stdio.h>
#include <stdlib.h>
int v, e;
typedef struct node {
int a;
int b;
int cost;
} node;
int compare(const void *a, const void *b) {
const node *x = *(node **)a;
const node *y = *(node **)b;
return (x->cost > y->cost) ? 1 : 0;
}
int main() {
scanf("%d %d", &v, &e);
int i;
node *arr[e];
for (i = 0; i < e; i++) {
int a, b, cost;
scanf("%d %d %d", &a, &b, &cost);
arr[i] = (node *)malloc(sizeof(node));
arr[i]->a = a;
arr[i]->b = b;
arr[i]->cost = cost;
}
qsort(arr, e, sizeof(node *), compare);
printf("\n\n");
for (int i = 0; i < e; i++) {
printf("%d %d %d\n", arr[i]->a, arr[i]->b, arr[i]->cost);
}
return 0;
}
:
9 14
2 5 4
7 8 7
0 1 4
1 7 11
0 7 8
7 6 1
6 5 2
5 4 10
3 5 14
3 4 9
2 3 7
1 2 8
2 8 2
8 6 6
输出:
2 5 4
2 8 2
0 1 4
8 6 6
6 5 2
7 6 1
7 8 7
2 3 7
1 2 8
0 7 8
3 4 9
5 4 10
1 7 11
3 5 14
前几行未按照输出对定位进行正确排序。请帮助我。
I am trying to sort an array of structs using qsort
, but it's not properly sorting the content.
The structure node consists of the starting vertex, the ending vertex, and the cost of reaching from vertex 'a' to vertex 'b'.
I am writing the code for Kruskal's algorithm
#include <stdio.h>
#include <stdlib.h>
int v, e;
typedef struct node {
int a;
int b;
int cost;
} node;
int compare(const void *a, const void *b) {
const node *x = *(node **)a;
const node *y = *(node **)b;
return (x->cost > y->cost) ? 1 : 0;
}
int main() {
scanf("%d %d", &v, &e);
int i;
node *arr[e];
for (i = 0; i < e; i++) {
int a, b, cost;
scanf("%d %d %d", &a, &b, &cost);
arr[i] = (node *)malloc(sizeof(node));
arr[i]->a = a;
arr[i]->b = b;
arr[i]->cost = cost;
}
qsort(arr, e, sizeof(node *), compare);
printf("\n\n");
for (int i = 0; i < e; i++) {
printf("%d %d %d\n", arr[i]->a, arr[i]->b, arr[i]->cost);
}
return 0;
}
Input:
9 14
2 5 4
7 8 7
0 1 4
1 7 11
0 7 8
7 6 1
6 5 2
5 4 10
3 5 14
3 4 9
2 3 7
1 2 8
2 8 2
8 6 6
Output:
2 5 4
2 8 2
0 1 4
8 6 6
6 5 2
7 6 1
7 8 7
2 3 7
1 2 8
0 7 8
3 4 9
5 4 10
1 7 11
3 5 14
The first few rows are not sorted properly as per the output. Please help me out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
比较函数必须返回以下值之一,即负,零或正值,具体取决于第一个比较的元素大于,等于或小于降次排序的第二个元素。
因此此功能定义
不正确。
相反,您可以编写以下方式(前提是您要按升序排列数组
,以降序对数组进行排序,那么比较功能可以看起来像是
一个演示程序。
程序输出是
The comparison function must return one of the following values, negative, zero or positive value, depending on whether the first compared elements is greater than, equal to or less than the second compared element for the descending sorting.
So this function definition
is incorrect.
Instead you could write the following way (provided that you are going to sort the array in the descending order
If you want to sort the array in the ascending order then the comparison function can look like
Here is a demonstration program.
The program output is