c语言中的折半排序法是怎样的,基本程序是怎样的
折半法
应该叫做2分法。
用2分法查找数
需要先对数组进行排序(升序或降序)
假如你所要查找的数是20
数组是 1 4 7 8 20 30 34
每次都拿中间的数跟你要比的数比
也就是 8和20比
发现20比8大
所以左面的数都不要了
剩下的是 20 30 34
再拿20跟30比
发现20比30小
右面的数都不要了
再拿20跟20比
相等,则找到了。
如果找不到返回-1
下面是程序。
#include <iostream>
using namespace std;
int binarysearch(int* data,int low,int high,int value)
{
int k=(low+high)/2;
if(value<*(data+low)||value>*(data+high))
{
return -1;
}
if(value<*(data+k))
{
return binarysearch(data,low,k-1,value);
}
else if(value>*(data+k))
{
return binarysearch(data,k+1,high,value);
}
else
return k;
}
void main()
{
int pos;
int arr1[9]={1,2,3,4,5,6,7,8,9};
int i=9;
while(i)
{
pos=binarysearch(arr1,0,8,i);
cout<<"数字"<<i<<"的下标是:"<<pos<<endl;
i--;
}
pos=binarysearch(arr1,0,8,20);
cout<<"数字20的下标是:"<<pos<<endl;
}
-
上一篇:c语言的折半查找法
-
下一篇:C语言 折半查找法