1. 程式人生 > >折半查詢(遞迴)

折半查詢(遞迴)

//
//  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;
}