结构体多条件排序
请问下怎么对结构体的元素进行快速排序?
怎么qsort?
struct aa{
int x;
int y;
char name[10];
}a[10];
请问下怎么对上面的结构体进行快排?
考虑优先x> y> name
就是说x相等的情况下就看y的大小再name的大小,
请给点思路,谢谢
[解决办法]
给你,你可以运行一下.
#include <iostream>
#include <sstream>
using namespace std;
struct aa{
int x;
int y;
char name[10];
}a[10];
int compare(const void* a, const void* b)
{
struct aa *a1 = (struct aa *) a;
struct aa *a2 = (struct aa *) b;
if(a1-> x != a2-> x)
return (a1-> x - a2-> x) ;
else if(a1-> y != a2-> y)
return (a1-> y - a2-> y) ;
else
return strcmp(a1-> name, a2-> name);
}
int main()
{
for (int i=0; i <10; i++)
{
a[i].x=10-i;
a[i].y=10+i;
}
a[1].x=10;
a[6].x=5;
strcpy(a[0].name, "hello ");
strcpy(a[1].name, "pello ");
strcpy(a[2].name, "ahdello ");
strcpy(a[3].name, "xhello ");
strcpy(a[4].name, "zhello ");
strcpy(a[5].name, "hdello ");
strcpy(a[6].name, "dvhello ");
strcpy(a[7].name, "hhello ");
strcpy(a[8].name, "uhello ");
strcpy(a[9].name, "phello ");
cout < < "Before sort .... " < <endl;
for (int i=9; i> =0; --i)
cout < <a[i].x < < " " < <a[i].y < < " " < <a[i].name < <endl;
qsort(a, 10, sizeof(aa), compare);
cout < < "After sort .... " < <endl;
for (int i=0; i <=9; ++i)
cout < <a[i].x < < " " < <a[i].y < < " " < <a[i].name < <endl;
}