标签:
二分查找代码:
//============================================================================ // Name : BinarySearch.cpp // Author : Danny // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> using namespace std; int binarySearch(int a[], int left, int right, int k) { if (left > right) return -1; int mid = (left + right) / 2; if (a[mid] == k) { return mid; } else if (a[mid] > k) { return binarySearch(a, left, mid - 1, k); } else { return binarySearch(a, mid + 1, right, k); } } int main() { int a[5] = { 1, 2, 4, 5, 7 }; int index = binarySearch(a, 0, 4, 7); cout << index << endl; return 0; }
标签:
原文地址:http://www.cnblogs.com/chen0958/p/4525296.html