45 lines
1.2 KiB
C
45 lines
1.2 KiB
C
#include "c_BinaryInsertionSort.h"
|
|
#include <stdlib.h>
|
|
#include <stdio.h>
|
|
|
|
typedef struct {
|
|
char name[20];
|
|
double price;
|
|
} Product;
|
|
|
|
// 自定义比较函数:按价格 (price) 升序排列
|
|
int compareProductsByPrice(const void* a, const void* b) {
|
|
const Product* p1 = (const Product*)a;
|
|
const Product* p2 = (const Product*)b;
|
|
|
|
if (p1->price < p2->price) return -1;
|
|
if (p1->price > p2->price) return 1;
|
|
return 0;
|
|
}
|
|
|
|
int main() {
|
|
// 准备一个商品数组
|
|
Product shop[] = {
|
|
{"Laptop", 4500.0},
|
|
{"Phone", 3200.0},
|
|
{"Mouse", 150.0},
|
|
{"Tablet", 3200.0}, // 测试稳定性:单价和 Phone 相同
|
|
{"Keybd", 299.0}
|
|
};
|
|
size_t count = sizeof(shop) / sizeof(shop[0]);
|
|
|
|
printf("排序前:\n");
|
|
for (size_t i = 0; i < count; i++) {
|
|
printf("商品: %-8s | 价格: %.2f\n", shop[i].name, shop[i].price);
|
|
}
|
|
|
|
// 调用通用折半插入排序
|
|
c_BinaryInsertionSort(shop, count, sizeof(Product), compareProductsByPrice);
|
|
|
|
printf("\n排序后(按价格升序):\n");
|
|
for (size_t i = 0; i < count; i++) {
|
|
printf("商品: %-8s | 价格: %.2f\n", shop[i].name, shop[i].price);
|
|
}
|
|
|
|
return 0;
|
|
} |