Home >Backend Development >C#.Net Tutorial >Introduction to binary search in C# (code introduction)
This article uses an introductory case (code) of binary search to introduce to you what binary search is in C#? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Binary search: applicable to sorted arrays
1. Binary search (entry case)
static void Main(string[] args) { int[] myNums = {1,13,22,34,56,143,167,211,266,363,466,572,595,645,688,689,702,779,888,899,922}; Console.WriteLine("我的数组是:"); for(int i = 0; i < myNums.Length; i++) { Console.Write("{0} ", myNums[i]); } Console.WriteLine(); //使用二分法从数组查找指定值 //取得查找值在数组中的索引位置 int QueryValueIndex = QueryFromTwoParts(688, myNums, 0, myNums.Length - 1); Console.WriteLine("--------------------------------------------------------"); Console.WriteLine("查找值688在数组中的索引位置是:{0}", QueryValueIndex); Console.WriteLine("数组myNums索引位置{0}处的值是:{1}", QueryValueIndex, myNums[QueryValueIndex]); Console.ReadKey(); } //该方法返回的是查找值在数组中的索引位置 private static int QueryFromTwoParts(int QueryValue, int[] nums, int leftIndex, int rightIndex) { //计算数组中间值的在数组中的索引位置 int midValueIndex = (leftIndex + rightIndex + 1) / 2; //取得数组中间索引位置处的值 int midValue = nums[midValueIndex]; //比较中间值与查找值的大小,确定下一步该怎样继续查询 if(QueryValue == midValue) { return midValueIndex; } else if(QueryValue < midValue) { return QueryFromTwoParts(QueryValue, nums, leftIndex, midValueIndex); } else { return QueryFromTwoParts(QueryValue, nums, midValueIndex, rightIndex); } }
2. Code running results:
The above is the detailed content of Introduction to binary search in C# (code introduction). For more information, please follow other related articles on the PHP Chinese website!