现在的位置: 首页 > 综合 > 正文

基于visual Studio2013解决面试题之1307二分查找

2013年01月24日 ⁄ 综合 ⁄ 共 739字 ⁄ 字号 评论关闭


题目

解决代码及点评

/*
    二分查找实现
*/

#include <iostream>
using namespace std;


int BinarySearch(int *pnArr, int nLen, int nValue)
{
    if (pnArr == NULL || nLen < 1)
    {
        return -1;
    }
    int nLeft = 0;
    int nRight = nLen - 1;
    while (nLeft <= nRight)
    {
        int nMid = nLeft + (nRight - nLeft) / 2;
        if (pnArr[nMid] == nValue)
        {
            return nMid;
        }
        else if (pnArr[nMid] > nValue)
        {
            nRight = nMid - 1;
        }
        else
        {
            nLeft = nMid + 1;
        }
    }
    return -1;
}
int main()
{
    int nArr[] = {1,2,5,7,9,11,14,16,19};
    int nLen = sizeof(nArr) / sizeof(int);
    int Result = BinarySearch(nArr, nLen, 21);
    if (Result != -1)
    {
        cout<<"找到该数据在数组的下标为:"<<Result<<endl;
    }
    else
    {
        cout<<"没有该数据"<<endl;
    }

    system("pause");
    return 0;
}

代码下载及其运行

代码下载地址:http://download.csdn.net/detail/yincheng01/6704519

解压密码:c.itcast.cn

下载代码并解压后,用VC2013打开interview.sln,并设置对应的启动项目后,点击运行即可,具体步骤如下:

1)设置启动项目:右键点击解决方案,在弹出菜单中选择“设置启动项目”

2)在下拉框中选择相应项目,项目名和博客编号一致

抱歉!评论已关闭.