递增有序数组中,查找某一个数字的位置

时间:2020-12-11 10:31:37
// 递增有序数组中,查找某一个数字的位置
#include <stdio.h>
int foo(int  p[], int s, int e, int value) 
{ 
	if (s>e)
	{
		printf("Can't find [%d]\n",value);
		return -1;
	}
	int m = (s+e)/2;
	if (p[m] == value)
	{
		printf("[%d] in position: %d\n",value,m);
		return value;
	}
	

	if (p[m] <p[e] && p[m] >p[s])
	{
		if (value<=p[m])
		{
			e = m-1;
		}else
			s = m+1;

	}else if (p[m] <p[e] && p[m] <p[s])
	{
		if (value>=p[m] && value<=p[e])
		{
			s = m+1;
		}else
			e = m-1;
	}else
	{
		if (value<=p[m] && value>=p[s])
		{
			e=m-1;
		}else
			s = m+1;
	}	

	foo(p,s,e,value);
} 
void main() 
{ 
    int  p[]= {3,4,5,6,7,8,9,10,11,1,2}; 
    for (int i=0;i<12;i++)
    {
		foo(p,0,10,i);
    } 
}