码迷,mamicode.com
首页 > 编程语言 > 详细

算法6---查找

时间:2016-09-16 10:08:41      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

两种最基本的查找

1顺序查找

 1 void search(int a[],int n,int target)
 2 {
 3     int flag=0;
 4     for (int i = 0; i < n; i++)
 5     {
 6         if (a[i]==target)
 7         {
 8 
 9             flag=1;
10         }   
11     }
12     if (flag==1)
13     {
14         printf("using the first method  find it!\n");
15     }
16     else
17         printf("using the first method can‘t find it!\n");
18 }

 

2 二分查找

 1 int  search2(int a[],int n,int target)
 2 {
 3     int first=0;
 4     int last=n-1;
 5 
 6     while(first<last)
 7     {
 8         int mid=(first+last)/2;
 9         if (a[mid]==target)
10         {
11 
12             return 1;
13         }
14         else if (a[mid]>target)
15         {
16             last=mid-1;
17         }
18         else
19             first=mid+1;
20     }
21     return -1;
22 }

 

算法6---查找

标签:

原文地址:http://www.cnblogs.com/tao-alex/p/5875915.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!