二分查找法查找城市名称
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 }