[算法] 循环有序数组查找递归实现

有序数组二分查找的变形,代码如下:

#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);
}

  

posted @ 2014-12-13 09:52  ~嘉言懿行~~我是煲仔饭~~  阅读(199)  评论(0编辑  收藏  举报