最近开始学习C++,自己尝试先写一些基本的算法,欢迎拍砖。
基本的查找算法包括:顺序查找、折半查找、二叉树查找、索引查找、哈希表查找
顺序查找:
思路很简单,遍历判断即可,对数组无要求,适应最普通的情况,时间复杂度为O(n);
二分查找:
又叫折半查找,基本思路也很简单,每次查找规模减半,要求数组必须是有序的,时间复杂度为O(logn)
/*
二分查找,supposing the array is Ascending
*/
#include "iostream"
#include "vector"
using namespace std;
bool halfSearch(const int target,vector
&arrays);
int main()
{
vector
my_array;
int element(0);
int length(0);
int target(0);
int counter(0);
cout<<"Please input your array size:"<
>length;
cout<<"Please input your array: "<
>element;
my_array.push_back(element);
++counter;
}
cout<<"Please input your target value: "<
>target; bool result=halfSearch(target,my_array); if(result) cout<<"find it!"<
&arrays) { int start=0; int end=arrays.size()-1; int mid=0; while(start<=end)//for equal start and end { mid=start+((end-start)>>1); if(target==arrays[mid]) return true; if(target
注意上述代码中只是简单的返回元素是否存在,如果要返回元素的位置的时候,还要考虑一种情况是数组中存在多个相同元素,是否范围多个位置。
二叉树查找:
基本思路基本与二分查找一样,不再详述。
bool binaryTree_Search(const int target,const Node *root)
{
if(root==NULL)
return false;
if(root->m_value==target)
return true;
else if(root->m_value>target)
{
if(root->p_left!=NULL)
return binaryTree_Search(target,root->p_left);
else
return false;
}
else
{
if(root->p_right!=NULL)
return binaryTree_Search(target,root->p_right);
else
return false;
}
}
索引查找:
又称分块查找。把数组分成若干块,在每一块中的数据元素的存储顺序是任意的,但要求块与块之间须按关键字值的大小有序排列,还要建立一个按关键字值递增顺序排列的索引表,索引表中的一项对应线形表中的一块,索引项包括两个内容:① 键域存放相应块的最大关键字;② 链域存放指向本块第一个结点的指针。分块查找分两步进行,先确定待查找的结点属于哪一块,然后在块内查找结点。
哈希表查找:
哈希表查找是通过对记录的关键字值进行运算(自定义哈希函数),直接求出结点的地址,是关键字到地址的直接转换方法,不用反复比较。时间复杂度O(1)。