用qsort对结构体排序,急~~(在线等)

zhengwei1984222 2003-12-16 10:38:07
假如有一个结构体数组
struct node{
int x;
int y;}node[4]={4,y1,6,y2,1,y3,5,y4};
现在要根据node.X的值对数组进行排序,调用qsort函数怎么实现?
小弟一直对qsort函数的第四个参数不很明白,谁能帮忙解释一下!3x!


...全文
692 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhengwei1984222 2003-12-16
  • 打赏
  • 举报
回复
行了!
谢过各位!
arfi 2003-12-16
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <stdlib.h>

struct node
{
int x;
int y;
}node[4]={{4, 0}, {6, 0}, {1, 0}, {5, 0}};

int compare(const void *ele1, const void *ele2)
{
struct node *px, *py;

px = (struct node *)ele1;
py = (struct node *)ele2;

if(px->x < py->x)
return 1;
else
return 0;
}

void main(void)
{
int i;

qsort(node, 4, sizeof(struct node), compare);
for(i=0; i<4; i++)
printf("{%d, %d}, ", node[i].x, node[i].y);
}

第四个参数是一个函数指针,其中的参数是数组中两个元素的地址值(不用你管),你需要自己写一下比较函数,通过改变其返回值可进行从小到大或从大到小进行排序
lyr311 2003-12-16
  • 打赏
  • 举报
回复
去看看我曾经提过的这个问题吧:
http://expert.csdn.net/Expert/topic/2259/2259716.xml?temp=.3238489
layman2008 2003-12-16
  • 打赏
  • 举报
回复
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int compare( const void *arg1, const void *arg2 );

void main( int argc, char **argv )
{
int i;
/* Eliminate argv[0] from sort: */
argv++;
argc--;

/* Sort remaining args using Quicksort algorithm: */
qsort( (void *)argv, (size_t)argc, sizeof( char * ), compare );

/* Output sorted list: */
for( i = 0; i < argc; ++i )
printf( "%s ", argv[i] );
printf( "\n" );
}

int compare( const void *arg1, const void *arg2 )
{
/* Compare all of both strings: */
return _stricmp( * ( char** ) arg1, * ( char** ) arg2 );
}

看看这个例子
zhengwei1984222 2003-12-16
  • 打赏
  • 举报
回复
谁能帮忙写一下啊!
zhengwei1984222 2003-12-16
  • 打赏
  • 举报
回复
大哥,能不能说得明白点!
hanyixin 2003-12-16
  • 打赏
  • 举报
回复

第四个参数是一个函数指针,这个函数提供了比较的方法。

69,336

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧