问题描述:
给定一个整数X和整数A0,A1,...,A(N-1),后者已经预先排序并在内存中,求使得Ai=X的下标,如果X不在数据中,则返回i=-1.
算法描述:
int BinarySearch(const ElementType A[], ElementType X, int N) { int Low, Mid, High; Low = 0; High = N - 1; while(Low <= High) { Mid = (Low + High) / 2; if(A[Mid] < X) Low = Mid + 1; else if(A[Mid] > X) High = Mid - 1; else return Mid; /* Found */ } return NotFound; /* NotFound is defined as -1 */ }
算法时间复杂度为O(logN)。