二分查找
#include<iostream>
using namespace std;
int main(){
int a[10]={2,4,5,8,12,14,18,23,45,67};//只适用于已经排好序的数组的查找
int x=14;
int high=9;
int low=0;
while(high>=low){
if(x>a[(high+low)/2])
low=(high+low)/2;//如果x大于中间值,则比较右边
else if(x<a[(high+low)/2])
high=(high+low)/2;
else if(x==a[(high+low)/2])
return (high+low)/2;
}
return -1;
}
归并两个数组
#include<iostream>
using namespace std;
int main(){
int a[3]={1,3,18};
int b[5]={4,6,9,10,15};
int c[8];//将a和b合并到c中
int s=0,t=0,i=0;
while(s<3&&t<5){
if(a[s]<b[t])
{c[i]=a[s];
s++;
i++;
}
else if(a[s]>b[t])
{
c[i]=b[t];
t++;
i++;
}
}
if(s==3)
for(int j=t;t<5;t++)
{c[i]=b[t];
i++;
}
else if(t==5)
for(int k=s;s<3;s++)
{
c[i]=a[s];
i++;
}
for(int x=0;x<8;x++){
cout<<c[x]<<" ";
}
return 0;
}