折半查找(递归)
程序员文章站
2024-03-20 18:16:04
...
//
// main.cpp
// ni
//
// Created by 申凡 on 2018/11/21.
// Copyright © 2018年 申凡. All rights reserved.
//
#include <iostream>
using namespace std;
int BinarySearchRecur(int a[],int nLow,int nHigh,int k){
if (nLow>nHigh) return -1;
else
{
int mid=(nLow+nHigh)/2;
if (k==a[mid])
return mid;
else if (k<a[mid])
return BinarySearchRecur(a,nLow,mid-1,k);
else
return BinarySearchRecur(a,mid+1,nHigh,k);
}
}
int main(int argc, const char * argv[]) {
int n,a[100],k;
cout << "请输入元素个数" << endl;
cin >> n;
for(int i = 0 ; i < n ; i++)
cin >> a[i];
cout << "请输入想要查找的数字" << endl;
cin >> k;
cout << BinarySearchRecur(a, 0, n - 1, k);
return 0;
}
下一篇: 深入理解Cookie