折半查找 C++template

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

const int NOT_FOUND = -1;

vector<int> num;

template <typename Comparable>
int binarySearch(const vector<Comparable> & a, const Comparable & x)
{
    
    
    int low = 0, high = a.size() - 1;
    while (low <= high) {
    
    
        int mid = (low + high) / 2;
        if (a[mid] < x) low = mid + 1;
        else if (a[mid] > x) high = mid - 1;
        else return mid;
    }
    return NOT_FOUND;
}

int main()
{
    
    
    int n, t, x;
    cin >> n;
    for (int i = 0; i < n; i++) {
    
    
        cin >> t;
        num.push_back(t);
    }
    sort(num.begin(), num.end());
    cin >> x;
    int p = binarySearch(num, x);
    cout << p << endl;
    return 0;
}
#include <stdio.h>
#include <assert.h>

#define LEN 8
int a[LEN] = {
    
     2, 5, 7, 13, 14, 16, 17, 21 };

int is_sorted()
{
    
    
        int i, sorted = 1;
        for (i = 1; i < LEN; i++)
                sorted = sorted && a[i-1] <= a[i];
        return sorted;
}

int judge(int left, int right, int number)
{
    
    
        int i;
        for (i = 0; i < LEN; i++) {
    
    
                if (i >= left && i <= right)
                        continue;
                if (a[i] == number)
                        return 0;
        }
        return 1;
}

int binarysearch(int number)
{
    
    
        int mid, left = 0, right = LEN - 1;
        assert(is_sorted());
        while (left <= right) {
    
    
                assert(judge(left, right, number));
                mid = (left + right) / 2;
                if (a[mid] < number)
                        left = mid + 1;
                else if (a[mid] > number)
                        right = mid - 1;
                else
                        return mid;
        }
        assert(judge(left, right, number));
        return -1;
}

int main(void)
{
    
    
        int number;
        scanf("%d", &number);
        printf("%d\n", binarysearch(number));
        return 0;
}
                                                                                                                                                                                                 5,17          Top

猜你喜欢

转载自blog.csdn.net/qq_18431031/article/details/105981977
今日推荐