首页 > 代码库 > 二分查找 Binary Search

二分查找 Binary Search

简单地用递归的方法实现了二分查找算法,适用于数组。

二分查找算法的前提条件是数组本身是有序的,比如int arr[6] = {2, 3, 5, 7, 11, 13};

 

 1 int 2 BinarySearch(int arr[], int key, int left, int right) 3 { 4     if (left > right) {  5         return -1;  6     } 7      8     int middle = (left + right) / 2; 9     10     if (arr[middle] == key) {11         return middle;12     } else if (arr[middle] > key) {13         BinarySearch(arr, key, left, middle-1);14     } else if (arr[middle] < key) {15         BinarySearch(arr, key, middle+1, right);16     }17 }

 

二分查找 Binary Search