- 折半查找:有10个数按由小到大顺序存放在一个数组中,输入一个数,要求用折半查找法找出该数是数组中第几个元素的值。如果该数不在数组中,则打印出“None”
C语言c++不会写求学霸教一下
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
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"; }解决 无用评论 打赏 举报