算法不会,尚能饭否之折半查找(Binary search)

    已经好长时间没有写算法了,今天就写了一个简单的折半查找的算法,很简单。来瞧瞧吧!好了,现在就开始吧!

     所谓折半查找,哦,对了,以前的那篇折半排序博文,如果大家看过的话,折半查找那是小 case 了!当然不在话下了。

     何为折半查找,就是查找一个数是否在一个给定的排好序的序列中。每次从序列的中间开始比较,如果,中间的数要比你要查找的数字大,那就忽略中间以右的那一部分(当然,我的前提是,序列是升序排列的),就在左部分查找你要查找的值,如果找到了,恭喜你,否则,抱歉,没有找到。就是这个思想,很简单。好了,贴出我的代码,代码才能说明问题,是吧!

//BinarySearch.cpp #include <iostream> using namespace std; #define true 1 #define false 0 int BinarySearch(const int [], int, int); //Binary Search function int main() { int iNum; int iResult; int iValue; cout<<"Please input the number of Array:"; cin>>iNum; int *Array = new int[iNum]; //Input the elements of Array cout<<"Please input the elements of Array:"; for (int i = 0; i < iNum; ++i) { cin>>Array[i]; } cout<<"Please input the value which you want to search:"; cin>>iValue; iResult = BinarySearch(Array, iNum, iValue); if (1 == iResult) { cout<<iValue<<" is in the Array!"<<endl; } else { cout<<iValue<<" is not in the Array!"<<endl; } } //If succeed,return 1, else return 0 int BinarySearch(const int Array[], int num, int value) { int iLeft = 0; int iRight = num - 1; int iMiddle; while (iLeft <= iRight) { iMiddle = (iLeft + iRight) / 2; if (Array[iMiddle] < value) { iLeft = iMiddle + 1; } else if (Array[iMiddle] > value) { iRight = iMiddle - 1; } else { return 1; } } return 0; }

好了,代码,已经有了,如果还有什么问题, call me

转载于:https://www.cnblogs.com/JPAORM/archive/2011/04/04/2509893.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值