我想把最便宜的物品排在最前面。 c代码工作正常,我只是想知道是否有更好的方法在c中对结构进行排序?
typedef struct
{
float price;
char product[50];
char brand[50];
}clothes;
void sort(clothes*pt, int count)
{
int a, b;
float price;
char product[50];
char brand[50];
for(a = 0; a < count - 1; a++){
for(b = a + 1; b < count; b++){
if((pt+a)->price > (pt+b)->price){
price = ((pt+b)->price);
strcpy(product,(( pt+b)->product));
strcpy(brand,((pt+b)->brand));
((pt+b)->price) = ((pt+a)->price);
strcpy(((pt+b)->product),((pt+a)->product));
strcpy(((pt+b)->brand),((pt+a)->brand));
((pt+a)->price) = price;
strcpy(((pt+a)->product),product);
strcpy(((pt+a)->brand),brand);
}
}
}
}
答案 0 :(得分:2)
您可能,您可能应该使用标准排序函数qsort(3)。你需要给它一个比较函数。
static int compare_clothes_by_price (const void*p1, const void*p2)
{
const clothes* c1 = (const clothes*)p1;
const clothes* c2 = (const clothes*)p2;
if (c1->price == c2->price) return 0;
else if (c1->price < c2-price) return -1;
else if (c1->price > c2-price) return 1;
// this is reached only if a price is NAN
abort();
}
然后你打电话
qsort(pt, count, sizeof(clothes), compare_clothes_by_price);
答案 1 :(得分:2)
如果你想提高效率:
这与其他答案几乎相同,所以我不会再解释一些细节。
我的建议中的KEY差异在于,通过对指向结构的指针进行排序,每次qsort交换时都不需要复制整个结构的内容。
查看例如,其他答案如何通过sizeof(衣服):
qsort(pt, count, sizeof(clothes), compare);
这意味着当结构很大时,你需要更多的工作 如果你只是排序指针,它会更快。
qsort(pt, count, sizeof(clothes*), compare);
但您需要调整数组和比较函数
答案 2 :(得分:2)
您可以使用标准qsort()
。这是一个例子:
#include <stdio.h>
#include <stdlib.h>
typedef struct clothes {
float price;
char product[50];
char brand[50];
} clothes;
int sort_clothes(const void *s1, const void *s2) {
const struct clothes *c1 = s1;
const struct clothes *c2 = s2;
if (c1->price == c2->price) {
return 0;
} else if (c1->price < c2->price) {
return -1;
} else {
return 1;
}
}
void print_clothes(struct clothes * c, const size_t count)
{
for ( size_t i = 0; i < count; ++i ) {
printf("%s, %s: %f\n", c[i].product, c[i].brand, c[i].price);
}
}
int main(void)
{
struct clothes c[] = { {59.99, "Jeans", "Levi"},
{10.99, "T-shirt", "Acme"},
{5.99, "Socks", "Feet Inc."} };
printf("Before sorting...\n");
print_clothes(c, 3);
printf("\nAfter sorting...\n");
qsort(c, 3, sizeof *c, sort_clothes);
print_clothes(c, 3);
return 0;
}
输出:
paul@thoth:~/src/sandbox$ ./sortstruct
Before sorting...
Jeans, Levi: 59.990002
T-shirt, Acme: 10.990000
Socks, Feet Inc.: 5.990000
After sorting...
Socks, Feet Inc.: 5.990000
T-shirt, Acme: 10.990000
Jeans, Levi: 59.990002
paul@thoth:~/src/sandbox$