第十四周日志

#include<iostream>
int main(){
 using namespace std;
 int a[] = {1,3,4,5,7,9,11};
 int first = 0;
 int last = sizeof(a)/4-1;
 int c[last+1];
 int h;
 for(int j : a){
  cout<< j << "  ";
 }
 cout<<endl;
 cout<<"请输入要查找的数,没找到将自动插入";
 cin>>h;
 while (1)
 {
 if(h==a[0]){//查找输入的元素 ,用来处理头尾两个
 cout<<"已找到"<<h<<"在第"<<0<<"个元素"<<endl;
  return 0; 
 }else if(h==a[last]){
  cout<<"已找到"<<h<<"在第"<<last<<"个元素"<<endl;
  return 0;
 }
 
 if(h>a[(first+last)/2]){//查找输入的元素
  first=(first+last)/2;
 }else if(h<a[(first+last)/2]){
  last=(first+last)/2;
 }else if(h==a[(first+last)/2]){
  cout<<"已找到"<<h<<"在第"<<(first+last)/2<<"个元素"<<endl;
  return 0;
 }
 
 int b = last-first;
 if(b==1){//插入不存在的元素
  if(h<a[0] ){//处理最大和最小两个
  for(int i=sizeof(a)/4;i>=0;i--){
   c[i]=a[i-1];
   }
   c[0]=h;
   break;
  }else if(h>a[last]){
   for(int k=0;k<=sizeof(a)/4-1;k++){
   c[k]=a[k];
   } 
   c[sizeof(a)/4]=h;
   break;
  }
  for(int i=sizeof(a)/4;i>=first;i--){//处理中间的元素替换
   c[i]=a[i-1];
  }
  for(int k=0;k<=first;k++){
   c[k]=a[k];
  }
  c[last]=h;
  break;
 } 
   }
   for(int l=0;l<=7;l++){
  cout<< c[l] << "  ";
 }
}
posted @ 2020-06-03 14:27  阆涴  阅读(173)  评论(0)    收藏  举报