文章标题

来源:互联网 发布:数据存储安全 编辑:程序博客网 时间:2024/06/11 10:26

面试题

1、请实现二分查找法
答:

#include <iostream>using namespace std;const int g_nSize = 32;int FindValuePos(int (&arry)[g_nSize],  int nValue){    int nLeft = sizeof(arry) / sizeof(int) / 2;    int nPos = nLeft;    while (nLeft > 0)    {        nLeft = nLeft - nLeft / 2;        if (nValue < arry[nPos])        {            nPos -= nLeft;        }        else if (nValue > arry[nPos])        {            nPos += nLeft;        }        else        {            return nPos;        }    }    return -1;}int main(){    int arry[g_nSize];    for(int i = 0; i < g_nSize; i++)    {        arry[i] = i * 100;    }    cout << "Pos:" << FindValuePos(arry, 0) << endl;    system("pause");    return 0;}