数据结构——3种搜索

1.顺序搜索

2.基于顺序表的折半搜索

3.二叉搜索树

#include<iostream>
using namespace std;
int Seqsearch(int r[], int n, int k) {//顺序搜索(带哨兵)
	r[0] = k;
	while (r[n--] != k) {};
	return n+1;
}
int Binsearch1(int r[], int n, int k) {//顺序表的折半搜索(非递归)
	int low = 1, high = n;
	while (low <= high) {
		int middle = (low + high) / 2;
		if (r[middle] < k)low = middle + 1;
		else if (r[middle] > k)high = middle - 1;
		else return middle;
	}return 0;
}
int Binsearch2(int r[], int low, int high, int k) {//顺序表的这般搜索(递归)
	if (low > high)return 0;
	int middle = (low + high) / 2;
	if (r[middle] < k)Binsearch2(r, middle + 1, high, k);
	else if (r[middle] > k)Binsearch2(r, low, middle - 1,k);
	else return middle;
}
int main() {
	int a[101],n,x;
	scanf_s("%d", &n);
	for (int i = 1; i <= n; i++)scanf_s("%d", &a[i]);
	scanf_s("%d", &x);
	//cout<<Seqsearch(a, n, x);
	//cout<<Binsearch1(a, n, x);
	cout << Binsearch2(a, 1, n, x);
	return 0;
}
#include<iostream>
#include<algorithm>
using namespace std;
int tree[1001] = { 0 };
int sum = 0, n, x, a[1001];
void insert(int x)
{
    int t = 1;//从根节点开始
    while (tree[t] != 0){
        if (tree[t] > x) t *= 2;
        else t = t * 2 + 1;
    }
    tree[t] = x;
}
int find_x(int y)
{
    int t = 1;
    if (*find(a, a + n, y)) {
        while (tree[t] != y || tree[t] == 0){
            sum++;
            if (tree[t] > y) t *= 2;
            else t = t * 2 + 1;
        }
        if (!tree[t]) return -1;
        else return sum + 1;
    }
    else return -1;
}
int main()
{
    cin >> n;
    for (int i = 0; i < n; i++){
        cin >> a[i];
        insert(a[i]);
    }
    cin >> x;
    int ans = find_x(x);
    if (ans != -1) cout << ans;
    else cout << "NO";
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值