用C++实现查找算法

用C++实现一些查找算法。

测试代码

#include <iostream>
#include <algorithm>

using namespace std;

//顺序查找
int sselect(int a[], int len, int k) {
    for (int i = 0; i < len; i++) {
        if (k == a[i])
            return i;
    }
    return -1;
}

//折半查找(递归)
int binary_select(int a[], int low, int high, int k) {
    if (low > high) {
        return -1;
    } else {
        int mid = (low + high) / 2;
        if (k < a[mid]) {
            return binary_select(a, low, mid - 1, k);
        } else if (k > a[mid]) {
            return binary_select(a, mid + 1, high, k);
        } else
            return mid;
    }
}

//折半查找(非递归)
int binary_select2(int a[], int len, int k) {
    int low = 0, high = len - 1, mid;
    while (low <=high) {
        mid = (low + high) / 2;
        if (a[mid] == k)
            return mid;
        else if (k < a[mid])
            high = mid - 1;
        else
            low = mid + 1;
    }
    return -1;
}

//二叉树结点的定义
typedef struct BiNode {
    int data;
    struct BiNode *lchild, *rchild;
} BiNode, *BiTree;

//二叉排序树的插入
int insertBitree(BiTree &T, int x) {
    if (T = NULL) {
        T = (BiTree) malloc(sizeof(BiNode));
        T->data = x;
        T->lchild = NULL;
        T->rchild = NULL;
        return 1;
    } else if (x == T->data)
        return -1;
    else if (x < T->data)
        return insertBitree(T->lchild, x);
    else
        return insertBitree(T->rchild, x);
}

//二叉排序树的建立
void creatBitree(BiTree &T, int a[], int len) {
    T = NULL;
    int i = 0;
    while (i < len) {
        insertBitree(T, a[i]);
        i++;
    }
}

//二叉排序树的查找
int selectBitree(BiTree T, int x) {
    if (!T)
        return -1;
    else {
        if (x = T->data)
            return 1;
        else if (x < T->data)
            return selectBitree(T->lchild, x);
        else
            return selectBitree(T->rchild, x);
    }
}

//2 4 6 13 19 22 56 77 81
int main() {
    int n;
    cin >> n;
    int *nums = new int[n];
    for (int i = 0; i < n; i++) {
        cin >> nums[i];
    }


//    if (binary_select(nums, 0, n - 1, 22) != -1) {
//        cout << "该元素在数组中第" << binary_select(nums, 0, n - 1, 22) + 1 << "位";
//    } else {
//        cout << "未找到该元素";
//    }

//    if (sselect(nums, n, 77)) {
//        cout << "该元素在数组中第" << sselect(nums, n, 77) + 1 << "位";
//    } else
//        cout << "未找到该元素";

    if (binary_select2(nums, n, 19)) {
        cout << "该元素在数组中第" << binary_select2(nums, n, 19) + 1 << "位";
    } else
        cout << "未找到该元素";

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值