一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

在数组中查询指定字符函数

时间:2011-03-08 编辑:简简单单 来源:一聚教程网

在数组中查询指定字符函数

#include

using namespace std;

bool find(int a[], int n, const int &sum, int &x, int &y)
{
    int i = 0, j = n-1, csum;
    while (i < j)
    {
        csum = a[i] + a[j];
        if (csum == sum)
        {
            x = a[i];
            y = a[j];
            return true;
        }
        else if (csum < sum)
            i++;
        else
            j--;
    }
    return false;
}

int main()
{
    int a[] = {1, 4, 7, 11, 15};
    int x, y;
    if (find(a, 5, 15, x, y))
        cout<     return 0;
}

我们找到数组的第一个数字和最后一个数字。当两个数字的和大于输入的数字时,

把较大的数字往前移动;当两个数字的和小于数字时,把较小的数字往后移动;当

相等时,打完收工。这样扫描的顺序是从数组的两端向数组的中间扫描

热门栏目