ListSet_无序表搜索
最后更新于:2022-04-01 20:51:37
无序表搜索就是一个个的遍历, 从头开始逐个检查, 直到表中关键字值等于给定关键字值, 则查找成功. 或者查完整个表, 查找失败为止.
搜索失败的平均搜索长度:(n + 1) / 2.
实现代码:
~~~
#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
#include "assert.h"
using namespace std;
enum ResultCode
{
Underflow, Overflow, Success, Duplicate, NotPresent
};
template
class DynamicSet
{
public:
virtual ResultCode Search(T &x) const = 0; // 表中搜索与x关键字相同的元素, 若存在则赋值给x并且返回Success, 否则返回NotPresent
virtual ResultCode Insert(T &x) = 0; // 表中搜索与x关键字相同的元素, 若存在该元素, 赋值给x返回Duplicate, 若表已满返回Overflow, 若表未满返回Success
virtual ResultCode Remove(T &x) = 0; // 表中搜索与x关键字相同的元素, 若存在该元素, 赋值给x返回Success, 否则返回NotPresent
virtual bool IsEmpty() const = 0; // 集合为空返回true
virtual bool IsFull() const = 0; // 集合为满返回true
/* data */
};
template
class ListSet: public DynamicSet
{
public:
ListSet( int mSize );
~ListSet() { delete []l; }
bool IsEmpty() const { return n == 0; }
bool IsFull() const { return n == maxSize; }
ResultCode Search(T &x) const;
ResultCode Insert(T &x);
ResultCode Remove(T &x);
void Print();
private:
T *l;
int maxSize, n;
/* data */
};
template
void ListSet::Print()
{
for(int i = 0; i < n; ++i)
cout << l[i] << "\t";
cout << endl;
}
template
ListSet::ListSet(int mSize)
{
maxSize = mSize;
l = new T[maxSize];
n = 0;
}
template
ResultCode ListSet::Insert(T &x)
{
assert(!IsFull());
l[n++] = x;
return Success;
}
template
ResultCode ListSet::Remove(T &x)
{
}
template
ResultCode ListSet::Search(T &x) const
{
for(int i = 0; i < n; ++i)
if(l[i] == x) {
x = l[i];
return Success;
}
return NotPresent;
}
int main(int argc, char const *argv[])
{
ListSet ls(20);
int x = 34; ls.Insert(x);
x = 88; ls.Insert(x);
x = 77; ls.Insert(x);
x = 55; ls.Insert(x);
x = 44; ls.Insert(x);
x = 100; ls.Insert(x);
ls.Print();
x = 88;
if(ls.Search(x) == Success)
cout << "Found " << x << endl;
return 0;
}
~~~
';