当前位置: 代码迷 >> 综合 >> 折半查找源代码
  详细解决方案

折半查找源代码

热度:1   发布时间:2024-02-21 13:19:54.0

折半查找的源代码:

#include <iostream>
#include <cstdlib>
using namespace std;//折半查找算法(递归算法)
int BinSearch(int a[],int low,int high,int k) {int mid;if (low<=high) {            //当前区间存在元素时mid = (low + high) / 2; //求查找区间的中间位置if (a[mid]==k) {return mid;              //找到后返回其物理下标mid}if (a[mid]>k) {               //当a[mid]>k时,在a[low..mid-1]中递归查找return BinSearch(a,low,mid-1,k);}else {                               //当a[mid<k时,在a[mid+1..high]中递归查找return BinSearch(a, mid+1,high, k);}}else {return -1;                           //当前查找区间没有元素时返回-1}}int main() {int n = 0;cout << "请输入一个数组的元素个数" << endl;cin >> n;int *a = new int[n];cout << "请数组输入元素" << endl;for (int i = 0; i < n; i++) {cin >> a[i];}int k;cout << "请输入要查找的元素:" << endl;cin >> k;if (BinSearch(a, 0, n - 1, k)==-1) {cout << "该数组中没有" << k << "元素" << endl;}else {cout << "输出要查找的位置:" << BinSearch(a, 0, n - 1, k) << endl;}system("pause");}

输出结果:

请输入一个数组的元素个数
5
请数组输入元素
1 2 3 4 5
请输入要查找的元素:
5
输出要查找的位置:4
请按任意键继续. . .

  相关解决方案