# C#算法设计查找篇之02-二分查找

C#算法设计概述

## 示例

```public class Program {

public static void Main(string[] args) {
int[] array = { 8, 11, 21, 28, 32, 43, 48, 56, 69, 72, 80, 94 };

Console.WriteLine(BinarySearch(array, 80));
Console.WriteLine(BinarySearch(array, 66, 0, array.Length - 1));

}

private static int BinarySearch(int[] array, int key) {
//直接求解
var min = 0;
var max = array.Length - 1;
var mid = 0;
while (min <= max) {
mid = (min + max) >> 1;
if (array[mid] > key) {
max = mid - 1;
}
else if (array[mid] < key) {
min = mid + 1;
}
else if (array[mid] == key) {
return mid;
}
}
return -1;
}

private static int BinarySearch(int[] array, int key, int low, int high) {
//递归法
if (low > high) return -1;
var mid = (low + high) >> 1;
if (array[mid] > key)
return BinarySearch(array, key, low, mid - 1);
else if (array[mid] < key)
return BinarySearch(array, key, mid + 1, high);
else
return mid;
}

}```

C#开发笔记之06-为什么要尽可能的使用尾递归，编译器会为它做优化吗？

```10
-1```

## AlgorithmMan

AlgorithmMan by Iori，AlgorithmMan是使用C#开发的一套用于算法演示的工具。

(4)