有序 循环数组的二分查找

来源:互联网 发布:android实现java线程池 编辑:程序博客网 时间:2022/10/05 07:06

例如 10,11,12,13,14,1,2,3,4,5,6,7,8,9虽然整体上不是有序的,但是只是在某个节点进行了循环。在这样的数组中进行查找,可以使用二分查找法。但是需要判断选环节的位置。

int Find(int* source, int size, int num){if(NULL == source || size < 0){return -1;}if(1== size){if(num == source[0]){return 0;}else{return -1;}}if(2 == size){if(num == source[0]){return 0;}else if(num == source[1]){return 1;}else{return -1;}}if(source[0] <= num && source[size/2]> num){int ret = Find(source,size/2,num);if(-1 !=ret){return ret;}else{return -1;}}else if(source[size/2] <= num && source[size - 1]>= num){int ret = Find(source + size/2,(size + 1)/2,num);if(-1 !=ret){return ret + size/2;}else{return -1;}}else if(source[0] >= num && source[size/2]>= num && source[size/2 + 1] >= num && source[size - 1]>= num){if(source[0] <= source[size/2]){int ret = Find(source + size/2,(size + 1)/2 ,num);if(-1 !=ret){return ret + size/2;}else{return -1;}}else if(source[size/2] <= source[size - 1]){int ret = Find(source,size/2,num);if(-1 !=ret){return ret;}else{return -1;}}else{return -1;}}else if(source[0] <= num && source[size/2]<= num && source[size/2 + 1] <= num && source[size - 1]<= num){if(source[0] <= source[size/2]){int ret = Find(source + size/2,(size + 1)/2 ,num);if(-1 !=ret){return ret + size/2;}else{return -1;}}else if(source[size/2 + 1] <= source[size - 1]){int ret = Find(source,size/2,num);if(-1 !=ret){return ret;}else{return -1;}}else{return -1;}}else{return -1;}}