二分搜索c++实现及解释
2008-11-18 21:16 Iron 阅读(261) 评论(0) 编辑 收藏 举报#include <iostream>
#include <fstream>
using namespace std;
int binarySearch(int a[],int x,int n)
{
/*取中点元素,进行判断,大于则在右半部继续查找,小于则在左半部继续查找,循环这个过程
一旦某一段的中点元素等于目的元素,返回,左右计数器相交则表示没有该元素,返回-1;
*/
int left = 0;
int right = n-1;
int middle;
while(left <= right)
{
middle = (left + right)/2;
if(x == a[middle]) return middle;
if(x > a[middle])
{
left = middle + 1;
}
else
{
right = middle - 1;
}
//cout<<middle<<endl;
}
//cout<<middle<<endl;
return -1;//未找到所找元素,返回-1
}
int main()
{
int intArray[5];
ifstream myCin("input.txt");//从文件中输入测试数据 1 5 6 89 562
for( int i = 0; i < 5; i++ )
{
myCin>>intArray[i];
//cout<<intArray[i]<<endl;
}
myCin.close();
ofstream myCout("output.txt");//把运行结果输出到文件
int index = binarySearch(intArray,1,5);
cout << index << endl;
myCout << index << endl;
}
#include <fstream>
using namespace std;
int binarySearch(int a[],int x,int n)
{
/*取中点元素,进行判断,大于则在右半部继续查找,小于则在左半部继续查找,循环这个过程
一旦某一段的中点元素等于目的元素,返回,左右计数器相交则表示没有该元素,返回-1;
*/
int left = 0;
int right = n-1;
int middle;
while(left <= right)
{
middle = (left + right)/2;
if(x == a[middle]) return middle;
if(x > a[middle])
{
left = middle + 1;
}
else
{
right = middle - 1;
}
//cout<<middle<<endl;
}
//cout<<middle<<endl;
return -1;//未找到所找元素,返回-1
}
int main()
{
int intArray[5];
ifstream myCin("input.txt");//从文件中输入测试数据 1 5 6 89 562
for( int i = 0; i < 5; i++ )
{
myCin>>intArray[i];
//cout<<intArray[i]<<endl;
}
myCin.close();
ofstream myCout("output.txt");//把运行结果输出到文件
int index = binarySearch(intArray,1,5);
cout << index << endl;
myCout << index << endl;
}