6-10 二分查找 (20 分)
题目地址https://pintia.cn/problem-sets/15/problems/923
就是二分查找裸题,把程序读清楚就差不多了。
本地写的补全的裁判程序
//----------------------------------------------- //code by mile //compiled by clion //no bug //Always get ACCEPT //----------------------------------------------- #include <map> #include <queue> #include <stack> #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define MAXSIZE 10 #define NotFound 0 typedef int ElementType; typedef int Position; typedef struct LNode *List; struct LNode { ElementType Data[MAXSIZE]; Position Last; }; List ReadInput(); Position BinarySearch(List L, ElementType X); using namespace std; /*********************Start Here**********************************/ int main() { List L; ElementType X; Position P; L = ReadInput(); scanf("%d", &X); P = BinarySearch(L, X); printf("%d\n", P); return 0; } List ReadInput() { List L; int n; scanf("%d", &n); for(int i = 1; i <= n; i++) scanf("%d", &L->Data[i]); L->Last = n; return L; } Position BinarySearch(List L, ElementType X) { int l = 1, r = L->Last, ans = 0; while(l <= r) { int mid = (l+r)>>1; if(L->Data[mid] >= X) { ans = mid, r = mid-1; } else l = mid+1; } if(L->Data[ans] != X) return NotFound; else return ans; }
提交的函数部分代码
Position BinarySearch(List L, ElementType X) { int l = 1, r = L->Last, ans = 0; while(l <= r) { int mid = (l+r)>>1; if(L->Data[mid] >= X) { ans = mid, r = mid-1; } else l = mid+1; } if(L->Data[ans] != X) return NotFound; else return ans; }
MILE NEVER GIVE UP!!!