# 二分查找

[cpp]
#include <stdio.h>
#include <stdlib.h>
void sort(int score[],int n){
int i,j,k,t;
for(i=0;i<n-1;i++){
k=i;
for(j=i;j<n;j++){ if(score[k]>score[j])
k=j;
}
if(k!=j){
t=score[i];
score[i]=score[k];
score[k]=t;
}
}
}
int binary_chop(int score[],int n,int key)
{
int left=0,right=n-1,mid,ret=-1;
while(left<=right){
mid=(left+right)/2;
if(score[mid]==key)
{
ret=mid;
break;
}
else if(score[mid]<key)
left=mid+1;
else
right=mid-1;
}
return ret;
}
int main()
{
int score[10]={0},i,key,ret;
for(i=0;i<10;i++)
scanf("%d",&score[i]);
sort(score,10);
printf("Input key:n");
scanf("%d",&key);
ret=binary_chop(score,10,key);
if(ret==-1)
else
printf("%d %dn",ret,score[ret]);
return 0;
}
[/cpp]

# 简单的测试一下代码高亮插件而已

6 2 23 54 12 6 8

2 6 8 12 23 54

[code lang=”C”]

#include <stdio.h>
#include <stdlib.h>
void sort(int *p,int n)
{
int i,j,t,k;
for(i=0;i<n-1;i++)
{
k=i;
for(j=i;j<n;j++)
if(p[k]>p[j])
k=j;
if(k!=i)
{
t=p[i];
p[i]=p[k];
p[k]=t;
}
}
}
int main()
{
int *p;
int n,i;
scanf("%d",&n);
p=(int *)malloc(sizeof(int)*n);
for(i=0;i<n;i++)
scanf("%d",&p[i]);
sort(p,n);
for(i=0;i<n;i++)
printf("%d ",p[i]);
printf("n");
return 0;
}
[/code]

Get start!