我的二分查找法(递归)
//经典的二分查找法写法 template <typename T> int binary_search(T *array, int n, T value) { if(array == NULL) //判断array是否为空指针 { cout << "input array is NULL." << endl; return -1; } int left = 0, right = n-1; while(left <= right) { int middle = left + ((right - left)>>1); //用右移操作代替除2,提高效率 if(array[middle] > value) { right = middle - 1; } else if(array[middle] < value) { left = middle + 1; } else return middle; } return -1; } //我写的二分查找法,测试过也没有错误,递归的效率可能低了些 template <typename T> int binarySearch(T *array,int left, int right, T num) { assert(array != NULL); int mid = left + (right - left)/2; if(num == array[mid]) return mid; else if(num < array[mid]) right = mid - 1; else left = mid + 1; if(left > right) return -1; return binarySearch(array, left, right, num); } int main() { int a[]={4,4,5,6,7,7,9,42}; cout<<binarySearch(a,0,sizeof(a)/sizeof(int),9)<<endl; system("pause"); return 0; }
网络上志同道合,我们一起学习网络安全,一起进步,QQ群:694839022