标签:style blog color ar sp div log bs ef
简单地用递归的方法实现了二分查找算法,适用于数组。
二分查找算法的前提条件是数组本身是有序的,比如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 }
标签:style blog color ar sp div log bs ef
原文地址:http://www.cnblogs.com/nipan/p/4052756.html