首页 > 代码库 > 算法6---查找

算法6---查找

两种最基本的查找

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     else17         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         else19             first=mid+1;20     }21     return -1;22 }

 

算法6---查找