---\n"); } void EmptyContact(pContact pc)//清空 { assert(pc); pc->count = 0; memset(pc->data, 0, sizeof(pc->data));//初始化函数 printf("清空通讯录成功!\n"); } void SortContact(pContact pc)//排序所有联系人函数 { assert(pc); if (pc->count == 0) { printf("通讯录为空\n"); return; } int input = 0; Sort_list();//排序方式的选项 printf("请选择按什么方式排序:"); assert(1 == scanf("%d", &input)); switch (input) { case NAME_SORT: bubble_sort(pc->data, pc->count, sizeof(PeoInfo), cmp_name);//以名字排序 break; case AGE_SORT: bubble_sort(pc->data, pc->count, sizeof(PeoInfo), cmp_age);//以年龄排序 break; case PHONE_SORT: bubble_sort(pc->data, pc->count, sizeof(PeoInfo), cmp_phone);//以电话排序 break; case ADDRESS_SORT: bubble_sort(pc->data, pc->count, sizeof(PeoInfo), cmp_address);//以地址排序 break; default: printf("选择错误,请重新选择\n"); break; } printf("通讯录排序成功!\n"); }
Bubble_sort定义函数的实现
#define _CRT_SECURE_NO_WARNINGS 1
#include
#include
#include
#include
#include "Contact.h" #include "Bubble_sort.h" int cmp_name(const void* e1, const void* e2)//比较名字 { assert(e1&&e2); return (strcmp(((PeoInfo *)e1)->name, ((PeoInfo *)e2)->name)); } int cmp_age(const void* e1, const void* e2)//比较年龄 { assert(e1&&e2); return (*(PeoInfo *)e1).age - (*(PeoInfo *)e2).age; } int cmp_phone(const void* e1, const void* e2)//比较电话 { assert(e1&&e2); return (strcmp(((PeoInfo *)e1)->phone, ((PeoInfo *)e2)->phone)); } int cmp_address(const void* e1, const void* e2)//比较地址 { assert(e1&&e2); return (strcmp(((PeoInfo *)e1)->address, ((PeoInfo *)e2)->address)); } void SWAP(char *e1, char *e2, int width)//交换信息 { int i = 0; assert(e1&&e2); for (i = 0; i < width; i++) { char tmp = *((char*)e1 + i); *((char*)e1 + i) = *((char*)e2 + i); *((char*)e2 + i) = tmp; } } void bubble_sort(void *base, int sz, int width, int(*cmp)(const void *e1, const void *e2))//排序 { int i = 0; int j = 0; assert(base&&cmp); for (i = 0; i < sz - 1; i++) { for (j = 0; j < sz - 1 - i; j++) { if (cmp((char *)base + width*j, (char *)base + width*(j + 1))>0) SWAP((char *)base + width*j, (char *)base + width*(j + 1), width); } } }
main函数的实现
#define _CRT_SECURE_NO_WARNINGS 1
#include
#include
#include
#include "Contact.h" #include "Bubble_sort.h" int main() { Contact my_con; void(*Opion[8])(pContact) = { 0, AddContact, DeleteContact, SearchContact, ModifyContact, ShowContact, EmptyContact, SortContact }; int input = 0; InitContact(&my_con);//初始化通讯录 do { menu(); printf("请选择操作功能:"); assert(1==scanf("%d", &input)); Opion[input](&my_con);//使用函数指针数组选择功能,作用相当于switch选择语句 } while(input); system("pause"); return 0; }