折半查詢法
阿新 • • 發佈:2018-12-16
題目描述: 分析: 經典二分查詢演算法,實現出來很簡單。 程式碼:
#include<iostream> #include<string> #include<Windows.h> #include<cstring> #define MAXN 10010 using namespace std; int main() { int n, val; int a[MAXN]; int st, en, mid; cin >> n; st = 1;en = n; for (int i = 1;i <= n;i++) cin >> a[i]; cin >> val; while (st <= en) { mid = (st + en) >> 1; if (a[mid] == val) { cout << mid << endl; system("pause"); return 0; } else if (a[mid] > val) { en = mid - 1; } else st = mid + 1; } cout << "-1" << endl; system("pause"); return 0; }