输入两个城市名查找其间的距离。
FindCityInsorArray用二分查找法在全局函数cityTable中查找城市名对应的下标值。
/* malloc example: random string generator*/
#include <stdio.h> /* printf, scanf, NULL /
#include <stdlib.h> / malloc, free, rand */
#define NCities 8
#define TRUE 1
static char * cityTable[NCities] = {
“beijing”, “chengdu”, “chongqing”, “dalian”, “guiyang”, “lanzhou”, “nanjing”, “sanya”
};
static int kmTable[NCities][NCities] = {
{0, 1697, 2695, 937, 1784, 1356, 926, 2543},
{1697, 0, 313, 1840, 533, 940, 1409, 1505},
{2695, 313, 0, 1734, 343, 1117, 1206, 1306},
{937, 1840, 1734, 0, 1995, 1594, 818, 2602},
{1784, 533, 343, 1995, 0, 1113, 1346, 976},
{1356, 940, 1117, 1594, 1113, 0, 1654, 2075},
{926, 1409, 1206, 818, 1346, 1654, 0, 1806},
{2543, 1505, 1306, 2602, 976, 2075, 1806, 0}
};
int main (){
int city1,city2;
city1 = GetCity(“input first city name:”);
city2 = GetCity(“input secend city name:”);
printf(“distant: %d km.\n”,cityTable[city1],cityTable[city2],kmTable[city1][city2]);
return 0;
}
static int GetCity(char * prompt){
char * cityName;
int index;
cityName = (char*)malloc(20*sizeof(char));
while(TRUE){
printf("%s",prompt);
gets(cityName); expand1 expand2
index = FindCityInSortArray(cityName);
if(index >= 0) break;
printf(“no city.\n”);
}
free(cityName);
return index;
}
二分查找法:
static int FindCityInSortArray(char * key){
int lh,rh,mid,cmp;
lh = 0;
rh = NCities - 1;
while(lh<= rh){
mid = (lh + rh) / 2;
cmp = strcmp(key, cityTable[mid]); expand3 expand4
if(cmp == 0) return mid;
if(cmp < 0){
rh = mid -1;
}
else{
lh = mid +1;
}
}
return(-1);
}
C++ 读取键盘输入(cin/