问题描述:
给定一递增有序数组a[0,1,…,n-1],请在数组中搜索给定元素。 搜索过程中请使用mid=(low+high)/2。搜索成功输出success及父亲,否则输出not found及父亲。
输入示例:
2
7 10 1 3 5 7 9 11 13
7 10 2 4 6 8 10 12 14
输出示例:
not found, father is 9
success, father is 12
代码:
// Created by 胡昱 on 2018/10/8. // Copyright © 2018年 胡昱. All rights reserved. #includeusing namespace std; // 存储结果的结构体 struct Result{ bool isSuccess = false; int father = 0; }; // 二分查找函数 Result BinarySearch(int* a, const int n, const int x) { // 初始化结果存储结构 Result result; // 在数组 a[0], ..., a[n-1] 中寻找 x int left = 0, right = n-1, middle = (left + right) / 2; while(left <= right) { if(x < a[middle]) { right = middle - 1; } else if(x > a[middle]) { left = middle + 1; } else { result.isSuccess = true; return result; } // 寻找新的中线 result.father = a[middle]; middle = (left + right) / 2; } // 没有找到 result.isSuccess = false; return result; } int main(int argc, const char * argv[]) { // 共有m个问题 int m; cin >> m; while((m--) > 0) { // 输入数组以及要寻找的数 int n; cin >> n; int x; cin >> x; int * array = new int[n]; for(int i = 0; i < n; ++i) { cin >> array[i]; } // 二分查找并输出结果 Result result = BinarySearch(array, n, x); if(result.isSuccess) { cout << "success, father is " << result.father << endl; } else { cout << "not found, father is " << result.father << endl; } // 释放资源 delete [] array; } }



