二分法查找:適用於已經排序好的數組
1.二分法查找(入門案例)
1 static void Main(string[] args) 2 { 3 int[] myNums = { 1, 13, 22, 34, 56, 143, 167, 211, 266, 363, 466, 572, 595, 645, 688, 689, 702, 779, 888,899,922 }; 4 5 Console.WriteLine("我的數組是:"); 6 for (int i = 0; i < myNums.Length; i++) 7 { 8 Console.Write("{0} ",myNums[i]); 9 } 10 Console.WriteLine(); 11 12 //使用二分法從數組查找指定值 13 //取得查找值在數組中的索引位置 14 int QueryValueIndex = QueryFromTwoParts(688, myNums, 0, myNums.Length - 1); 15 Console.WriteLine("--------------------------------------------------------"); 16 Console.WriteLine("查找值688在數組中的索引位置是:{0}",QueryValueIndex); 17 Console.WriteLine("數組myNums索引位置{0}處的值是:{1}",QueryValueIndex,myNums[QueryValueIndex]); 18 19 Console.ReadKey(); 20 } 21 22 23 //該方法返回的是查找值在數組中的索引位置 24 private static int QueryFromTwoParts(int QueryValue, int[] nums, int leftIndex, int rightIndex) 25 { 26 //計算數組中間值的在數組中的索引位置 27 int midValueIndex = (leftIndex + rightIndex + 1) / 2; 28 29 //取得數組中間索引位置處的值 30 int midValue = nums[midValueIndex]; 31 32 //比較中間值與查找值的大小,確定下一步該怎樣繼續查詢 33 if (QueryValue ==midValue) 34 { 35 return midValueIndex; 36 } 37 else if (QueryValue<midValue) 38 { 39 return QueryFromTwoParts(QueryValue, nums, leftIndex, midValueIndex); 40 } 41 else 42 { 43 return QueryFromTwoParts(QueryValue, nums, midValueIndex, rightIndex); 44 } 45 46 }
2.代碼運行結果: