本程序利用基数排序的思想对一批具有结构特征的汽车牌照进行排序,并且利用二分查找的思想对排好序的汽车牌照进行查找。运行程序时,输入一组要求的数据后,按要求操作,进行排序,查询时程序查找到匹配的数据,输出该关键字的其他信息。数据包括3项,分别为牌照的号码,车的型号,车主的姓名,其中牌照的一项输入形式为01B7328,前两位代表地区,字母代表车的使用类型,后四位代表车号,查询时要求输入正确的车牌号码。
#include <stdio.h>
#include <string.h>
#define N 20
struct Car
{
char numberPlate[8];
char model[10];
char owner[32];
};
void swap(struct Car *a, struct Car *b)
{
struct Car t = *a;
*a = *b;
*b = t;
}
void sort(struct Car *cars, int n)
{
for (int i = 0; i < n - 1; i++)
for (int j = i + 1; j < n; j++)
if (strcmp(cars[i].numberPlate, cars[j].numberPlate) > 0)
swap(&cars[i], &cars[j]);
}
struct Car *search(struct Car *cars, int n, const char *numberPlate)
{
int left = 0, right = n - 1, mid;
while (left < right)
{
if (strcmp(cars[left].numberPlate, numberPlate) == 0)
return &cars[left];
if (strcmp(cars[right].numberPlate, numberPlate) == 0)
return &cars[right];
mid = left + (right - left) / 2;
int r = strcmp(cars[mid].numberPlate, numberPlate);
if (r == 0)
return &cars[mid];
else if (r > 0)
right = mid;
else
left = mid;
}
return NULL;
}
int main()
{
struct Car cars[N];
char numberPlate[8];
int n;
printf("请输入汽车数目:\n");
scanf("%d", &n);
printf("请输入汽车的牌照、型号、车主姓名:\n");
for (int i = 0; i < n; i++)
scanf("%s%s%s", cars[i].numberPlate, cars[i].model, cars[i].owner);
printf("请输入查询汽车的牌照:\n");
scanf("%s", numberPlate);
struct Car *car = search(cars, n, numberPlate);
if (car)
printf("牌照: %s, 型号: %s, 车主: %s\n", car->numberPlate, car->model, car->owner);
else
printf("查无此车\n");
return 0;
}
#define N 10
#include<stdio.h>
#include<string.h>
struct Car
{
char license_plate[20];
char type[20];
char name[20];
};
void Swap(struct Car *str1, struct Car *str2)
{
struct Car tem = *str1;
*str1 = *str2;
*str2=tem;
}
void Ordor(struct Car car[N], int n)
{
int i = 0;
for (i = 0; i < n-1; i++)
{
int j = 0;
for (j = 0; j < n - 1 - i; j++)
{
if (strcmp(car[j].license_plate, car[j + 1].license_plate) > 0)
{
Swap(&car[j], &car[ + 1]);
}
}
}
}
char search(struct Car car[N], int n, char license_plate[])
{
int left = 0; int right = n ;
while (1)
{
int mid = (left + right) / 2 + left;
if (mid == 0)
{
if (strcmp(car[mid].license_plate, license_plate)>0)
{
return 0;
}
if (strcmp(car[mid].license_plate, license_plate) == 0)
{
return 1;
}
}
if (strcmp(car[mid].license_plate, license_plate)>0)
{
right = mid;
}
else if (strcmp(car[mid].license_plate, license_plate)<0)
{
left = mid;
}
else
{
return mid;
}
}
}
int main()
{
struct Car car[N] = { 0 };
int n;
printf("请输入汽车数目:\n");
scanf("%d", &n);
printf("请输入汽车的牌照、型号、车主姓名:\n");
int i = 0;
for (i = 0; i < n; i++)
{
scanf("%s%s%s", &car[i].license_plate, &car[i].type, &car[i].name);
}
Ordor(car,n);
char license_plate[20] = { 0 };
while (1)
{
printf("请输入查询汽车的牌照:\n");
scanf("%s", license_plate);
int ret = search(car, n, license_plate);
if (ret)
{
printf("牌号:%s,型号:%s,车主:%s\n", car[ret-1].license_plate, car[ret-1].type, car[ret-1].name);
break;
}
else
printf("无此车\n");
}
return 0;
}