查找算法相关代码

SearchFunc.h

//
//  SearchFunc.hpp
//  FirstP
//
//  Created by 赫赫 on 2023/11/1.
//

#ifndef SearchFunc_hpp
#define SearchFunc_hpp

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;

#endif /* SearchFunc_hpp */

//顺序查找表结构
//时间复杂度O(n)
typedef struct{
    int *elem;      //动态数组基址
    int TableLen;   //表长度
}SSTable;

//顺序查找(哨兵方式,数据从下标1开始存,下标0的位置存放查找关键字,即“哨兵”)
int Search_Seq(SSTable st,int key);

//折半查找,又称二分查找,仅适用于有序顺序表
//时间复杂度O(log(n))
int Binary_Search(SSTable st,int key);

SearchFunc.cpp

//
//  SearchFunc.cpp
//  FirstP
//
//  Created by 赫赫 on 2023/11/1.
//  查找算法代码

#include "SearchFunc.hpp"

//顺序查找(哨兵方式,数据从下标1开始存,下标0的位置存放查找关键字,即“哨兵”)
//时间复杂度O(n)
int Search_Seq(SSTable st,int key){
    st.elem[0]=key;
    int i;
    //从表尾开始向前查找
    for(i=st.TableLen;st.elem[i]!=key;i++);
    //如果i=0,那么就意味着没有查找到,否则返回数据存放下标
    return i;
}

//折半查找,又称二分查找,仅适用于有序顺序表(默认升序)
//时间复杂度O(log(n))
int Binary_Search(SSTable st,int key){
    int low=0,high=st.TableLen-1,mid;
    while(low<=high){
        mid=(low+high)/2;
        if(st.elem[mid]==key){
            return mid;
        }else if(st.elem[mid]>key){
            high=mid-1;
        }else{
            low=mid+1;
        }
    }
    return -1;//表示没有找到元素
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值