分段查找。
代码实现(数组是降序排列):
void binary_searching(int *num, int number, int start, int end)
{
if(number>=num[end] && number<=num[start])
{
int mid = (start + end)/2;
int i;
if(number == num[mid])
{
cout << "你所要寻找的数在这个数组里第 ";
for(i=0; num[mid-i]==number && (mid-i)>=start; i++)
cout << mid-i << " ";
for(i=1; num[mid+i]==number && (mid+i)<=end; i++)
cout << mid+i << " ";
cout << "个。";
return;
}
else if(start == end)
{
cout << "你所要寻找的数不在这个数组里。";
return;
}
else if(number>num[mid])
{
binary_searching(num, number, start, mid);
}
else
{
binary_searching(num, number, mid+1, end);
}
}
else
{
cout << "你所要寻找的数不在这个数组里。";
return;
}
}
void Tsearching(int *num, int number, int start, int end)
{
int lmid = (start+end)/3;
int rmid = 2*(start+end)/3;
if(number>=num[end] && number<=num[start])
{
int i;
if(number==num[lmid])
{
cout << "你所要寻找的数在这个数组里第 ";
for(i=0; num[lmid-i]==number && (lmid-i)>=start; i++)
cout << lmid-i << " - ";
for(i=1; num[lmid+i]==number && (lmid+i)<=end; i++)
cout << lmid+i << " +";
cout << "个。";
return;
}
else if(number==num[rmid])
{
cout << "你所要寻找的数在这个数组里第 ";
for(i=0; num[rmid-i]==number && (rmid-i)>=start; i++)
cout << rmid-i << " ";
for(i=1; num[rmid+i]==number && (rmid+i)<=end; i++)
cout << rmid+i << " ";
cout << "个。";
return;
}
else if(start == end)
{
cout << "你所要寻找的数不在这个数组里。";
return;
}
else if(number>num[lmid])
{
Tsearching(num, number, start, lmid);
}
else if(number<num[lmid]&&number>num[rmid])
{
Tsearching(num, number, lmid, rmid);
}
else if(number<num[rmid])
{
Tsearching(num, number, rmid, end);
}
}
else
{
cout << "你所要寻找的数不在这个数组里。";
return;
}
}