vb手机号码抽奖程序_vb抽奖小程序_vb60抽奖程序(3)

电脑杂谈  发布时间:2017-02-24 04:05:29  来源:网络整理

void main()

{ int a[10],p,x,i;

printf('please input the array:/n');

for(i=0;i<10;i++)

scanf('%d',&a[i]);

printf('please input the number you want find:/n');

scanf('%d',&x);

printf('/n');

p=0;

while(x!=a[p]&&p<10)

p++;

if(p>=10)

printf('the number is not found!/n');

else

printf('the number is found the no%d!/n',p);

}

思考:将上面程序改写一查找函数Find,若找到则返回下标值,找不到返回-1

②基本思想:一列数放在数组a[1]---a[n]中,待查找的关键值为key,把key与a数组中的元素从头到尾一一进行比较查找,若相同,查找成功,若找不到,则查找失败。(查找子过程如下。index:存放找到元素的下标。)

void main()

{ int a[10],index,x,i;

printf('please input the array:/n');

for(i=0;i<10;i++)

scanf('%d',&a[i]);

printf('please input the number you want find:/n');

scanf('%d',&x);

printf('/n');

index=-1;

for(i=0;i<10;i++)

if(x==a[i])

{ index=i; break;

}

if(index==-1)

printf('the number is not found!/n');

else

printf('the number is found the no%d!/n',index);

}

2.折半查找法(只能对有序数列进行查找)

基本思想:设n个有序数(从小到大)存放在数组a[1]----a[n]中,要查找的数为x。用变量bot、top、mid分别表示查找数据范围的底部(数组下界)、顶部(数组的上界)和中间,mid=(top+bot)/2,折半查找的算法如下:

(1)x=a(mid),则已找到退出循环,否则进行下面的判断;

(2)x

(3)x>a(mid),x必定落在mid+1和top的范围之内,即bot=mid+1;

(4)在确定了新的查找范围后,重复进行以上比较,直到找到或者bot<=top。

将上面的算法写成如下程序:

void main()

{

int a[10],mid,bot,top,x,i,find;

printf('please input the array:/n');

for(i=0;i<10;i++)

scanf('%d',&a[i]);

printf('please input the number you want find:/n');

scanf('%d',&x);

printf('/n');

bot=0;top=9;find=0;

while(bot

{ mid=(top+bot)/2;

if(x==a[mid])

{find=1;break;}

else if(x

top=mid-1;

else

bot=mid+1;

}

if (find==1)

printf('the number is found the no%d!/n',mid);


本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/ruanjian/article-34162-3.html

相关阅读
    发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

    热点图片
    拼命载入中...