朴素想法:
顺序遍历 复杂度 O(n);
int FoundIndex(int data[], int length)
{
for(int i = 0 ; i < length; ++i)
{
if(data[i] == i)
return i;
}
return -1;
}
利用升序的性质 二分查找 复杂度 O(log(n));
int FoundIndex(int data[], int length, int start, int end)
{
if(data== NULL || start < 0|| end > length)
{
return -1;
}
int mid = (start + end) /2;
if( data[mid] == mid)
{
return mid;
}
else if(data[mid] > mid)
{
end = mid-1;
return FoundIndex(data,length, start, end);
}
else if(data[mid] < mid)
{
start = mid+1;
return FoundIndex(data,length, start, end);
}
}
int main()
{
int data1[]= {2,2,2,4,6,7,7};
int length = sizeof(data1)/sizeof(data[0]);
cout<<FoundIndex(data1,length)<<endl;
cout<<FoundIndex(data1,length, 0,length -1)<<endl;
return 0;
}