查找算法相关代码

SearchFunc.h

cpp 复制代码
//
//  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

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;//表示没有找到元素
}
相关推荐
2301_8002561124 分钟前
第九章:空间网络模型(空间网络查询、数据模型、Connected、with Recursive、pgRouting)
网络·数据库·算法·postgresql·oracle
逑之1 小时前
C语言笔记10:sizeof和strlen,指针与数组
c语言·笔记·算法
求梦8201 小时前
【力扣hot100题】旋转图像(15)
算法·leetcode·职场和发展
C雨后彩虹6 小时前
任务最优调度
java·数据结构·算法·华为·面试
少林码僧8 小时前
2.31 机器学习神器项目实战:如何在真实项目中应用XGBoost等算法
人工智能·python·算法·机器学习·ai·数据挖掘
钱彬 (Qian Bin)8 小时前
项目实践15—全球证件智能识别系统(切换为Qwen3-VL-8B-Instruct图文多模态大模型)
人工智能·算法·机器学习·多模态·全球证件识别
Niuguangshuo8 小时前
EM算法详解:解密“鸡生蛋“的机器学习困局
算法·机器学习·概率论
a3158238068 小时前
Android 大图显示策略优化显示(一)
android·算法·图片加载·大图片
一条大祥脚9 小时前
26.1.9 轮廓线dp 状压最短路 构造
数据结构·c++·算法
鲨莎分不晴9 小时前
反向传播的数学本质:链式法则与动态规划的完美共舞
算法·动态规划