void Main() { List<string> s = new List<string>(){}; for(int i=0;i<10000;i++) { s.Add(i.ToString()); } s.Sort(); Stopwatch sw0 = new Stopwatch(); sw0.Start(); for(int i=0;i<10000;i++) { var k0 = s.Contains(i.ToString()); } sw0.Stop(); sw0.Elapsed.Dump(); Stopwatch sw1 = new Stopwatch(); sw1.Start(); for(int i=0;i<10000;i++) { var k1 = s.Exists(it=>it==i.ToString()); } sw1.Stop(); sw1.Elapsed.Dump(); Stopwatch sw2 = new Stopwatch(); sw2.Start(); for(int i=0;i<10000;i++) { var k2 = BinarySearch(s,i.ToString()); } sw2.Stop(); sw2.Elapsed.Dump(); } public static bool BinarySearch(List<string> list, string value) { int min = 0; int max = list.Count; while (min < max) { int mid = (max + min) / 2; string midItem = list[mid]; int comp = midItem.CompareTo(value); if (comp < 0) { min = mid + 1; } else if (comp > 0) { max = mid - 1; } else { return true;//midItem; } } if (min == max && min!=list.Count&& list[min].CompareTo(value) == 0) { return true; } return false; }
三个的执行时间。 拆半查找要求得要求先排序。
00:00:00.7093621
00:00:06.7513154
00:00:00.0159961
时间: 2024-11-05 02:20:44