二分查找法查找城市名称

 1 class City
 2 {
 3     public string CityName { get; set; }
 4 
 5     public int Start { get; set; }
 6 
 7     public int End { get; set; }
 8 
 9     public bool IsCurrentCity(int num)
10     {
11         return  (num >= Start && num <= End);
12 }
13 } 14 15 class CityHelper 16 { 17 List<City> cityList = null; 18 19 public string GetCityName(int num) 20 { 21 cityList = GetCityList(); 22 23 string name = null; 24 int start = 0; 25 int end = cityList.Count - 1; 26 27 while (end >= start) 28 { 29 int middle = (start + end) / 2; 30 31 if (cityList[middle].IsCurrentCity(num)) 32 { 33 name = cityList[middle].CityName; 34 break; 35 } 36 37 if (cityList[middle].End < num) 38 start = middle + 1; 39 else if (cityList[middle].End > num) 40 end = middle - 1; 41 } 42 43 return name; 44 } 45 46 List<City> GetCityList() 47 { 48 if (cityList == null)//判断为空再创建 49 { 50 cityList = new List<City>(); 51 52 City model = new City(); 53 model.CityName = "北京"; 54 model.Start = 1310000; 55 model.End = 1310000 + 875; 56 cityList.Add(model); 57 58 model = new City(); 59 model.CityName = "天津"; 60 model.Start = 1311000; 61 model.End = 1311000 + 275; 62 cityList.Add(model); 63 64 model = new City(); 65 model.CityName = "石家庄"; 66 model.Start = 1312000; 67 model.End = 1312000 + 875; 68 cityList.Add(model); 69 70 model = new City(); 71 model.CityName = "济南"; 72 model.Start = 1313500; 73 model.End = 1313500 + 75; 74 cityList.Add(model); 75 } 76 return cityList; 77 } 78 }

 

转载于:https://www.cnblogs.com/ZL1911/archive/2013/01/23/2872508.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值