标签:blog io ar for on div log 代码 amp
有序数组二分查找的变形,代码如下:
#include<stdio.h> #include<stdlib.h> 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(array, 16, 10); printf("%d", ret); return 0; } 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 CyclicOrderedBinarySearch(int *array, int begin, int end, int theNum) { 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)) { return CyclicOrderedBinarySearch(array, begin, mid, theNum); } else { return CyclicOrderedBinarySearch(array, mid + 1, end, theNum); } } else { if(contains(array, mid + 1, end, theNum)) { return CyclicOrderedBinarySearch(array, mid + 1, end, theNum); } else { return CyclicOrderedBinarySearch(array, begin, mid, theNum); } } return -1; } int search(int *array, int n, int theNum) { return CyclicOrderedBinarySearch(array, 0, n - 1, theNum); }
标签:blog io ar for on div log 代码 amp
原文地址:http://www.cnblogs.com/igloo1986/p/4160965.html