查找算法相关代码

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;//表示没有找到元素
}
相关推荐
To_OC12 小时前
LC 51 N 皇后:我以为难的是回溯,结果栽在了对角线下标
javascript·算法·leetcode
2401_8414956413 小时前
【操作系统】进程同步与互斥实验报告
c++·算法·操作系统·进程·并发·同步·互斥
爱刷碗的苏泓舒17 小时前
PPP-AR 中的参考星选取:数学原理、评价指标与切换处理
算法·gnss·模糊度固定·ppp-ar·星间单差·参考星·卫星端偏差
烬羽19 小时前
递归老写崩?一个"退回"公式,把回溯题变成填空题
javascript·深度学习·算法
闪电悠米19 小时前
力扣hot100-41.缺失的第一个正数-原地哈希详解
数据结构·算法·哈希算法
WL学习笔记20 小时前
堆(数据结构)
数据结构·
星空露珠20 小时前
28种颜色对应名称,
开发语言·数据库·算法·游戏·lua
QXWZ_IA1 天前
桥梁数字孪生怎么落地?
人工智能·科技·算法·智能硬件·政务
Kel1 天前
输出层与反分词(Output Layer & Detokenization)
人工智能·算法·架构