《算法图解》C1-二分查找

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Richard__Ting/article/details/89453023

《算法图解》C1-二分查找

// @version: 19.1
// @author: PzLu
// @Revision: 19.4.22

#include <iostream>
using namespace std;

// @brief: count the length of the array 
// @param: the array
// @return: the length 
template<class T>
int getArrLength(T& a){
    return sizeof(a)/sizeof(a[0]);
}

// @brief: judge if it can search the number
// @param: the array, the number, the length
void binarySearch(int array[], int key, int n){
    double minIndex = 0;
    double maxIndex = n - 1;
    int flag = 0;

    while(minIndex <= maxIndex){
        int midIndex = int((minIndex + maxIndex)/2);
        //cout << midIndex << endl;
        int tmp = array[midIndex];
        if(key == tmp){
            flag = 1; // find the number
            cout << "FIND THE NUMBER!" << endl;
            cout << "THE INDEX OF THE NUMBER " << key << " IS " << midIndex << "." << endl;
            maxIndex = -1;
        }
        else if(key < tmp){
            maxIndex = midIndex - 1; // pay attention to this.
        }
        else{
            minIndex = midIndex + 1; // pay attention to this.
        }
    }
    if(!flag){cout << "CANNOT FIND THE NUMBER " << key << "!" << endl;}
}

// @brief: main function
int main(){
    int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    binarySearch(arr, 7, getArrLength(arr));
    cout << endl;
    binarySearch(arr, 11, getArrLength(arr));
    return 0;
}
FIND THE NUMBER!
THE INDEX OF THE NUMBER 7 IS 6.

CANNOT FIND THE NUMBER 11!

猜你喜欢

转载自blog.csdn.net/Richard__Ting/article/details/89453023
今日推荐