- /// <summary>
- /// 二分法查找
- /// </summary>
- /// <param name="arr"></param>
- /// <param name="key">要查找的对象</param>
- public static int BinarySearch(int[] arr,int value)
- {
- int low = 0;
- int high = arr.Length - 1;
- while(low<=high)
- {
- int middle = (low + high) / 2;
- if (value == arr[middle])
- {
- return middle;//如果找到了就直接返回这个元素的索引
- }
- else if(value >arr[middle])
- {
- low = middle + 1;
- }
- else
- {
- high = middle - 1;
- }
- }
- return -1;//如果找不到就返回-1;
- }
-
|