Advertisement
Tony041010

比較循序檢查法和二分法的檢查次數

Dec 24th, 2020
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.59 KB | None | 0 0
  1. #include<bits\stdc++.h>
  2. using namespace std;
  3. int main(){
  4.     int piece,piece2;
  5.     string check_number;
  6.     cin>>piece;
  7.     string list[piece];
  8.     for(int i=0;i<piece;i++){
  9.         cin>>list[i];
  10.     }
  11.    
  12.     for(int q=0;q<piece;q++){
  13.     //循序檢查法
  14.         if(list[q]=="A734"){
  15.             cout<<q+1<<endl;
  16.         }
  17.         else{continue;}
  18.     }
  19.     sort(list,list+piece);
  20.    
  21.     //二分檢查法
  22.     int times=1;   
  23.     int L=0,R=piece-1,M;
  24.     while(L<=R){
  25.         M=int((L+R)/2);
  26.         if(list[M]=="A734"){
  27.         break;
  28.         }
  29.         else if(list[M]>"A734"){
  30.             R=M-1;
  31.             times++;
  32.         }
  33.         else{
  34.             L=M+1;
  35.             times++;
  36.         }  
  37.     }
  38.     cout<<times<<endl;
  39.     return 0;
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement