0
点赞
收藏
分享

微信扫一扫

C语言 线性查找

#include <stdio.h>
&nbsp;
&nbsp;#define&nbsp;NUMBER&nbsp;10
&nbsp;#define&nbsp;FAILED&nbsp;-1
&nbsp;
&nbsp;int&nbsp;search(const&nbsp;int&nbsp;v[],&nbsp;int&nbsp;value,&nbsp;int&nbsp;n)
&nbsp;{
&nbsp; int&nbsp;i&nbsp;=&nbsp;0;
&nbsp; &nbsp;
&nbsp; while&nbsp;(true){
if&nbsp;(i&nbsp;==&nbsp;n){
return&nbsp;FAILED;
}else&nbsp;if&nbsp;(v[i]&nbsp;==&nbsp;value){
return&nbsp;i;
}
i++;
}
&nbsp;&nbsp;}&nbsp;
&nbsp;&nbsp;
&nbsp;&nbsp;int&nbsp;main&nbsp;(void){
&nbsp;&nbsp; int&nbsp;i,&nbsp;value,&nbsp;key;
&nbsp;&nbsp; int&nbsp;num[NUMBER];
&nbsp;&nbsp;
&nbsp;&nbsp; for&nbsp;(i&nbsp;=&nbsp;0;&nbsp;i&nbsp;&lt;&nbsp;NUMBER;&nbsp;i++){
printf(&quot;num[%d]:&quot;,&nbsp;i);
scanf(&quot;%d&quot;,&nbsp;&amp;num[i]);
}
printf(&quot;要查找的值:&quot;);
scanf(&quot;%d&quot;,&nbsp;&amp;value);

key&nbsp;=&nbsp;search(num,&nbsp;value,&nbsp;NUMBER);

if(key&nbsp;==&nbsp;FAILED){
puts(&quot;查找失败。&quot;);
}else{
printf(&quot;%d&nbsp;是数组的第&nbsp;%d&nbsp;号元素。\n&quot;,&nbsp;value&nbsp;,&nbsp;key&nbsp;+&nbsp;1);
}

return&nbsp;0;
&nbsp;&nbsp;}

运行结果:
C语言 线性查找_i++
C语言 线性查找_数组_02
我们在search函数中加入2行代码打印出search函数查找的过程

#include <stdio.h>
&nbsp;
&nbsp;#define&nbsp;NUMBER&nbsp;10
&nbsp;#define&nbsp;FAILED&nbsp;-1
&nbsp;
&nbsp;int&nbsp;search(const&nbsp;int&nbsp;v[],&nbsp;int&nbsp;value,&nbsp;int&nbsp;n)
&nbsp;{
&nbsp; int&nbsp;i&nbsp;=&nbsp;0;
&nbsp; &nbsp;
&nbsp; while&nbsp;(true){
&nbsp;
if&nbsp;(i&nbsp;==&nbsp;n){
return&nbsp;FAILED;
}else&nbsp;if&nbsp;(v[i]&nbsp;==&nbsp;value){
printf(&quot;v[i]&nbsp;=&nbsp;%d&nbsp;==&nbsp;%d\n&quot;,&nbsp;v[i],&nbsp;value);&nbsp;&nbsp;// 打印查找过程
return&nbsp;i;
}
printf(&quot;v[i]&nbsp;=&nbsp;%d&nbsp;!=&nbsp;%d\n&quot;,&nbsp;v[i],&nbsp;value);&nbsp;&nbsp;&nbsp;// 打印查找过程
i++;
}
&nbsp;&nbsp;}&nbsp;
&nbsp;&nbsp;
&nbsp;&nbsp;int&nbsp;main&nbsp;(void){
&nbsp;&nbsp; int&nbsp;i,&nbsp;value,&nbsp;key;
&nbsp;&nbsp; int&nbsp;num[NUMBER];
&nbsp;&nbsp;
&nbsp;&nbsp; for&nbsp;(i&nbsp;=&nbsp;0;&nbsp;i&nbsp;&lt;&nbsp;NUMBER;&nbsp;i++){
printf(&quot;num[%d]:&quot;,&nbsp;i);
scanf(&quot;%d&quot;,&nbsp;&amp;num[i]);
}
printf(&quot;要查找的值:&quot;);
scanf(&quot;%d&quot;,&nbsp;&amp;value);

key&nbsp;=&nbsp;search(num,&nbsp;value,&nbsp;NUMBER);

if(key&nbsp;==&nbsp;FAILED){
puts(&quot;\a查找失败。&quot;);
}else{
printf(&quot;%d&nbsp;是数组的第&nbsp;%d&nbsp;号元素。\n&quot;,&nbsp;value&nbsp;,&nbsp;key&nbsp;+&nbsp;1);
}

return&nbsp;0;
&nbsp;&nbsp;}

运行结果:
C语言 线性查找_#define_03
C语言 线性查找_i++_04

函数search将传入的int类型的数组进行遍历,顺次查找是否存在与 value 相同的元素。如果有,则返回数组元素的下标。如果没有,则返回FAILED,也就是-1。
函数search 中 while 语句的控制表达式是 true ,因此只有在执行 return 语句的时候才能跳出循环,否则循环体将会一直重复执行下去。

总结:
在满足下述任意条件的时候,就可以跳出while语句。

  1. 未能找到想要查找的值,最后跳出循环(当 i == n 成立的时候)
  2. 找到了想要查找的值(当v[i] == value 成立的时候)


举报

相关推荐

0 条评论