查找算法相关代码

编程入门 行业动态 更新时间:2024-10-26 10:40:00

查找<a href=https://www.elefans.com/category/jswz/34/1770096.html style=算法相关代码"/>

查找算法相关代码

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;//表示没有找到元素
}

更多推荐

查找算法相关代码

本文发布于:2023-11-16 11:33:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1619720.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:算法   代码

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!