一.问题描述
编写程序: 用二分法在有序表{3,4,10,13,33,42,46,63,76,78,95,96,120}中查找一个给定的数。
二.设计思路
1.定义一个数组a存入上面的数,按从小到大排序
2.输入一个数n
3.设计一个函数f(a,0,13,n),取中间值mid=1+13/2,比较a[mid]和n的大小,若right-left>1&&a[mid]!=x,有若a[mid]>n,left=mid,right不变,则f(a,left,right,n)
若a[mid]<n,right=mid,left不变,f(a,left,right,n)否则若right-left<=1||a[mid]==n,若前者输出yes,否则no
三.流程图
四.代码实现
#include<iostream> using namespace std; void f(int* a, int n, int left, int right) { int mid = (left + right) / 2; if (right - left > 1 && a[mid] != n) { if (n > a[mid]) { left = (left + right) / 2; f(a, n, left, right); } if (n < a[mid]) { right = (left + right) / 2; f(a, n, left, right); } } if (right - left <= 1 || a[mid] == n) { if (a[mid] == n || a[mid + 1] == n) cout<<"yes"; else cout<<"no"; } } int main() { int n, right, left, a[13] = { 3,4,10,13,33,42,46,63,76,78,95,96,120 }; cin>>n; left = 0; right = 13; f(a, n, left, right); }
标签:13,right,int,每日,编程,mid,第十四天,left From: https://www.cnblogs.com/zhenaifen/p/17347681.html