1 #include <cstdio> 2 #include <cstdlib> 3 #include <ctime> 4 const int N=100; 5 int n=50,step; 6 int in[N]; 7 void binsort() 8 { 9 int l,r,id; 10 for (int i=1;i<n;i++) 11 { 12 l=0;r=i-1;int temp=in[i]; 13 while (l<=r) 14 { 15 int mid=(l+r)/2; 16 if (temp<in[mid]) 17 { 18 r=mid-1; 19 } 20 else 21 { 22 l=mid+1; 23 } 24 } 25 for (int j=i-1;j>=l;j--) 26 { 27 in[j+1]=in[j]; 28 } 29 in[l]=temp; 30 } 31 } 32 int binsearch(int want) 33 { 34 int l,r,mid; 35 l=0;r=n-1; 36 while (l<=r) 37 { 38 step++; 39 mid=(l+r)/2; 40 if (in[mid]==want) 41 { 42 return 1; 43 } 44 else if (in[mid]>want) 45 { 46 r=mid-1; 47 } 48 else 49 { 50 l=mid+1; 51 } 52 } 53 return 0; 54 } 55 int main() 56 { 57 srand(time(0)); 58 for (int i=0;i<n;i++) 59 { 60 in[i]=rand()%100; 61 printf("%d ",in[i]); 62 } 63 printf(" "); 64 binsort(); 65 for (int i=0;i<n;i++) 66 { 67 printf("%d ",in[i]); 68 } 69 printf(" "); 70 int ans,want; 71 step=0; 72 scanf("%d",&want); 73 ans=binsearch(want); 74 printf("%d step:%d ",ans,step);//注意不能写成printf("%d step:%d ",binsearch(want),step);!!! 75 76 return 0; 77 }