非递归实现
#include<stdio.h>
#include<stdlib.h> int isOrdered(int *array, int begin, int end) { return *(array+end) > *(array+begin) ? 1 : 0; } int contains(int *array, int begin, int end, int theNum) { return theNum >= *(array + begin) && theNum <= *(array + end) ? 1 : 0; } int CyclicOrderedBinarySearchNonRecursively(int *array, int begin, int end, int theNum) { while(end >= begin) { if(begin == end) { if(*(array + begin) == theNum) { return begin; } else { return -1; } } int mid = (begin + end) / 2; if(isOrdered(array, begin, mid)) { if(contains(array, begin, mid, theNum)) { end = mid; } else { begin = mid + 1; } } else { if(contains(array, mid + 1, end, theNum)) { begin = mid + 1; } else { end = mid; } } } return -1; } int search_nonrecursively(int *array, int n, int theNum) { return CyclicOrderedBinarySearchNonRecursively(array, 0, n - 1, theNum); } int main() { int *array = (int *)malloc(sizeof(int)*16); int i; for(i = 0; i < 16; i++) { *(array + i) = (i+5) % 16; }
int ret = search_nonrecursively(array, 16, 10); printf("%d ", ret); return 0; }