2301_81076548 2023-11-25 21:49 采纳率: 0%
浏览 8

C语言c++不会写求学霸教一下

  1. 折半查找:有10个数按由小到大顺序存放在一个数组中,输入一个数,要求用折半查找法找出该数是数组中第几个元素的值。如果该数不在数组中,则打印出“None”
  • 写回答

3条回答 默认 最新

  • VRJerry 2023-11-26 00:56
    关注

    下面的仅做参考,不敢说就是你说的折半查找。。。

    #include <iostream>
    using namespace std;
    
    int main()
    {
        int a[10];
        int findValue;
        int upLimit=9, downLimit=0;
        for (int i = 0; i < 10; i++)
            cin >> a[i];
        cin >> findValue;
    
        if (findValue<a[0] || findValue>a[9])
            cout << "None";
    
        while (upLimit - downLimit>1)
        {
            int testIndex = (upLimit + downLimit) / 2;
            if (findValue == a[testIndex])
            {
                cout << testIndex;
                return 0;
            }
            if (findValue < a[testIndex])
                upLimit = testIndex;
            else
                downLimit = testIndex;
        }
    
        if (findValue == a[upLimit])
            cout << upLimit;
        else if (findValue == a[downLimit])
                cout << downLimit;
         else
                cout << "None";
    
    }
    
    评论

报告相同问题?

问题事件

  • 创建了问题 11月25日