#include <stdio.h>
#include <time.h>
#include<iostream>
using namespace std;
void array_sort(int a[], int n);
int zhebancz(int a[], int n,int num);
int main()
{
int a[15];
int n,i;
srand( (unsigned)time( NULL ) );
for(i=0;i<15;i++)
{
a[i] = rand()%1000;
}
cout<<"Sorted order:"<<endl;
array_sort(a,15);
//=======输出排序完成的数组====
for(i=0;i<15;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
cout<<"please input a number:\n";
cin>>n;
//================折半查找==========
cout<<endl;
zhebancz(a,15,n);
return 0;
}
void array_sort(int a[],int n)
{
int i,j,k,tool;
for(i=0;i<n;i++)
{
k=i;
for(j=(i+1);j<n;j++)
{
if(a[j]<a[k])
{
tool=a[j];
a[j]=a[k];
a[k]=tool;
}
}
}
}
int zhebancz(int a[],int n,int num)
{
int inum = num;
int top,bottom,mid;
int flag=1; //如果在表列中找到数字,则值为1,否则为0
int loc=-1;//要查找的数在表列中的位置,如果loca=-1表示表列中没有这个数;如果有这个数,则它的值为所在的位置
flag=1; //假设输入的数在表列中
top=n;
bottom=0;
mid=(top+bottom)/2;
while(flag)
{
if( (inum>a[top]) || (inum<a[bottom]) ) //输入的数 num>a[top] 或者 num<a[bottom],肯定num不在这个表列中
{
loc=-1;
flag=0;
}
else if(a[mid]==inum) //如果num 等于找到的数
{
loc=mid;
printf("找到数 %d 的位置是:%d \n",num,loc+1);
return 1;
}
else if(a[mid]>inum) //若 a[mid]>num,则num 一定在 a[bottom]和a[mid-1]范围之内
{
top=mid-1;
mid=(top+bottom)/2;
}
else if(a[mid]<inum) //若 a[mid]<num,则num 一定在 a[mid+1]和a[top]范围之内
{
bottom=mid+1;
mid=(top+bottom)/2;
}
}
printf("没有找到数 %d 的位置 %d \n",num,loc);
return -1;
} 原文:http://blog.csdn.net/syytem004/article/details/41594167