二分查找 插值查找

二分查找

mid, min, max,
每次将target(即要查找的数)与中间位置进行比较,如果刚好等于直接找到,如果大于,往中间位置的右边找,如果小于,往中间位置的左边找
递归

// attention: the array must be sort
// 查找之前数组已经排好顺序
#include <iostream>
#include <vector>
using namespace std;

int count = 0;  // to calculate how many times has been compared

int binarySearch(vector<int> data, int target, int min, int max) {
    int mid = (min + max)/2;
    if (min > max) {
        count++;
        return -1;
    }
    if (target == data[mid]) {
        count++;
        return mid;
    }
    else if (target > data[mid]) {
        count++;
        return binarySearch(data, target, mid + 1, max);
    }
    else {
        count++;
        return binarySearch(data, target, min, mid - 1);
    }
}

int main() {
    int n, num;
    vector<int> data;
    cout << "total number : ";
    cin >> n;
    for (int i = 0; i < n; ++i) {
        cin >> num;
        data.push_back(num);
    }
    int target;
    cout << "target : ";
    cin >> target;
    int position = binarySearch(data, target, 0, n - 1);
    cout << position << endl;
    cout << count << endl;
    return 0;
}

插值查找

插值查找跟二分查找基本是一样的,不同的是插值查找的中间位置的确定不仅跟位置有关,还与数值的大小有关.

//比较的时候不仅看位置,还与数值有关,所以比较的次数较少,更高效
//注意比较的前提是数组中的数字是已经排好顺序的
// 注意只适合于数值比较集中的数组的查找
#include <iostream>
#include <vector>
using namespace std;

int count = 0;

int searchValue(vector<int> data, int target, int min, int max) {
    if (min > max) {
        count++;
        return -1;
    }
// 在求中间位置的时候,关注数值的大小,从而使得更加靠近要查找的数字
    int mid = min + (target - data[min])*(max - min)/(data[max] - data[min]);
    if (data[mid] == target) {
        count++;
        return mid;
    }
    else if (target > data[mid]) {
        count++;
        return searchValue(data, target, mid + 1, max);
    }
    else {
        count++;
        return searchValue(data, target, min, mid - 1);
    }
}

int main() {
    int n, num;
    vector<int> data;
    cout << "total number : ";
    cin >> n;
    while (n--) {
        cin >> num;
        data.push_back(num);
    }
    int target;
    cout << "target : ";
    cin >> target;
    int result = searchValue(data, target, 0, data.size() - 1);
    cout << "result : " << result << endl;
    cout << "count : " << count << endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值