代码
#include <stdio.h> int binarySearch(int iList[], int iNum, int iX, int * pPos) { if(NULL == pPos) { return -1; } int i = 0, j = iNum; while(i < j) { printf("from [%d] to [%d] ", i, j); int iPos = (i + j) / 2; int iMid = iList[iPos]; if(iX == iMid) { *pPos = iPos; return 0; } else if (iX > iMid) { i = iPos + 1; } else { j = iPos - 1; } } if(iList[i] == iX) { *pPos = i; return 0; } *pPos = -1; return -1; } int main(int argc ,char * argv[]) { int iList[33] = {0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33}; int iPos = 0; int iNum = 33; int iX = 5; binarySearch(iList, iNum, iX, &iPos); printf("[%d] @ position [%d] ", iX, iPos); iX = 6; binarySearch(iList, iNum, iX, &iPos); printf("[%d] @ position [%d] ", iX, iPos); iX = 0; binarySearch(iList, iNum, iX, &iPos); printf("[%d] @ position [%d] ", iX, iPos); iX = 33; binarySearch(iList, iNum, iX, &iPos); printf("[%d] @ position [%d] ", iX, iPos); iX = -1; binarySearch(iList, iNum, iX, &iPos); printf("[%d] @ position [%d] ", iX, iPos); iX = 35; binarySearch(iList, iNum, iX, &iPos); printf("[%d] @ position [%d] ", iX, iPos); return 0; }
编译
$ g++ -o binarySearch binarySearch.cpp
运行
$ ./binarySearch from [0] to [33] from [0] to [15] from [0] to [6] from [4] to [6] [5] @ position [5] from [0] to [33] from [0] to [15] from [0] to [6] from [4] to [6] [6] @ position [-1] from [0] to [33] from [0] to [15] from [0] to [6] from [0] to [2] [0] @ position [0] from [0] to [33] from [17] to [33] from [26] to [33] from [30] to [33] from [32] to [33] [33] @ position [32] from [0] to [33] from [0] to [15] from [0] to [6] from [0] to [2] [-1] @ position [-1] from [0] to [33] from [17] to [33] from [26] to [33] from [30] to [33] from [32] to [33] [35] @ position [-1]
再见……