非递归二分查找

// BinarySearch.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #define ARRAYSIZE 9 int binarySearch(int* a, int size, int numSearched) { if((size <= 0) || a == NULL ) return -1; if(numSearched < a[0] || numSearched > a[size-1]) return -1; if(a[0] == numSearched) return 0; if(a[size - 1] == numSearched) return (size -1) ; int middle = (size)/2; int start = 0, end = size-1; //bool searched = true; while( a[middle] != numSearched) { if(start == middle) { return -1; } if( numSearched < a[middle] ) { end = middle; middle = (start + end)/2; } else { start = middle; middle = (start + end)/2; } } return middle; } int _tmain(int argc, _TCHAR* argv[]) { int a[ARRAYSIZE]; for(int i = 0; i < ARRAYSIZE; i++ ) { a[i] = i * 100; } for(int i = -1; i < 11; i++ ) { std::cout << binarySearch(a, ARRAYSIZE, i * 100); } //std::cout << binarySearch(a, 10, 800); return 0; }

你可能感兴趣的:(null)