算法分析第三次作业

1. 问题

  在一个排好序的数组T[1..n]中查找x,如果x在T中,输出x在T的下标j;如果x不在T中,输出j=0.

2. 解析

     遍历数组

      二分数组

3. 设计

      遍历数组的算法,就是一个个按顺序查询

      二分算法:判断一个搜索集,每次判断搜索集的中间,减去一半区间

   

4. 分析

    遍历算法:O(n)

    二分算法:O(logn)

5. 源码

    https://github.com/Tinkerllt/algorithm-work.git

 1 #include<stdio.h>
 2 #include<iostream>
 3 #include<cmath>
 4 #include<cstring>
 5 #include<algorithm>
 6 #include<bitset>
 7 #include<set>
 8 #include<deque>
 9 #include<queue>
10 #include<vector>
11 //#include<unordered_map>
12 #include<map>
13 #include<stack>
14 using namespace std;
15 #define ll long long
16 #define ull unsigned long long
17 #define pii pair<int,int>
18 #define Pii pair<ll,ll>
19 #define m_p make_pair
20 #define l_b lower_bound
21 #define u_b upper_bound 
22 const int inf=0x3f3f3f3f;
23 const ll linf=0x3f3f3f3f3f3f3f3f;
24 const int maxn=3e5+11;
25 const int maxm=2e3+11;
26 const int mod=1e9+7; 
27 const double eps=1e-5;
28 ll rd(){ll x = 0, f = 1; char ch = getchar();while (ch<'0' || ch>'9') { if (ch == '-')f = -1; ch = getchar(); }while (ch >= '0'&&ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); }return x * f;}
29 inline ll qpow(ll a,ll b,ll p){ll res=1;while(b){if(b&1){res*=a;res%=p;}b>>=1;a=a*a%p;}return res;}
30 inline ll gcd(ll a,ll b){if(b==0) return a;return gcd(b,a%b);}
31 //iterator 
32 //head
33 //priority_queue
34 int a[maxn];
35 int main(){
36     //std::ios::sync_with_stdio(false);
37     int n=rd();
38     for(int i=1;i<=n;i++) a[i]=rd();
39     sort(a+1,a+n+1);
40     //检索算法1 遍历
41     int m=rd();//检索的数字 
42     printf("Case 1:
");
43     for(int i=1;i<=n;i++){
44         if(a[i]>m){
45             puts("0");
46             break;
47         }
48         if(a[i]==m){
49             printf("%d
",i);
50             break;
51         }
52         if(i==n){
53             puts("0");
54             break;
55         }
56     } 
57     //二分检索
58     printf("Case 2:
");
59     int l=1,r=n; 
60     while(l<=r){
61         int mid=l+r>>1;
62         if(a[mid]<m) l=mid+1;
63         else r=mid-1;
64     }
65     if(l>n||a[l]!=m) puts("0");
66     else printf("%d
",l);
67 }
View Code
原文地址:https://www.cnblogs.com/tinkerx/p/12558532.html