二分查找——算法系列
二分查找有两个条件:
- 数组必须有序,无序数组查找之前需要先让其有序
- 只限于顺序存储结构
代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.Net; using System.Threading; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { List<int> list = new List<int>(); for (int i = 0; i < 2000; i++) { Thread.Sleep(1); list.Add(new Random((int)DateTime.Now.Ticks).Next(0, 100)); } list.OrderBy(single => single).ToList(); for (int i = 0; i < 100; i++) { Thread.Sleep(100); if (BinarySearch(list, i) == 1) Console.WriteLine("找到了"); else Console.WriteLine("没找到"); } Console.ReadLine(); } public static int BinarySearch(List<int> list, int key) { int low = 0; int high = list.Count - 1; while (low <= high) { int middle = (low + high) / 2; if (key == list[middle]) return 1; else if (key > list[middle]) low = middle + 1; else high = middle - 1; } return 0; } } }