码迷,mamicode.com
首页 > 编程语言 > 详细

ListSet_对半搜索的迭代算法

时间:2015-11-04 17:54:45      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:

递归函数效率低, 常使用相应的迭代算法.

mid, left, right均为元素下标, 如果当前表不为空, 则令x与l[mid]比较. 若两者相等, 则搜索成功. 若前者小于后者, 则继续查找左半部分, 否

则查找右半部分. 下标范围分别为[left, mid - 1], [mid + 1, right]. 如果当前搜索表为空表, 搜索失败返回NotPresent.


实现代码:

#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
#include "assert.h"
using namespace std;
const int MAXN = 9999;

enum ResultCode
{
    Underflow, Overflow, Success, Duplicate, NotPresent
};
template <class T>
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 T>
class ListSet: public DynamicSet<T>
{
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 <class T>
void ListSet<T>::Print()
{
	for(int i = 0; i < n; ++i)
		cout << l[i] << "\t";
	cout << endl;
}

template <class T>
ListSet<T>::ListSet(int mSize)
{
	maxSize = mSize;
	l = new T[maxSize];
	n = 0;
}

template <class T>
ResultCode ListSet<T>::Insert(T &x)
{
	assert(!IsFull());
	l[n++] = x;
	l[n] = MAXN;
	return Success;
}

template <class T>
ResultCode ListSet<T>::Remove(T &x)
{

}

template <class T>
ResultCode ListSet<T>::Search(T &x) const
{
	int mid, left = 0, right = n -1;
	while(left <= right) {
		mid = (left + right) / 2;
		if(x < l[mid]) right = mid - 1;
		else if(x > l[mid]) left = mid + 1;
		else {
			x = l[mid];
			return Success;
		}
	}
	return NotPresent;
}
int main(int argc, char const *argv[])
{
	ListSet<int> ls(20);
	int x = 21; ls.Insert(x); 
	x = 30; ls.Insert(x);
 	x = 36; ls.Insert(x); 
	x = 41; ls.Insert(x);
 	x = 52; ls.Insert(x); 
	x = 54; ls.Insert(x);
	x = 66; ls.Insert(x); 
	x = 72; ls.Insert(x);
	x = 83; ls.Insert(x); 
	x = 97; ls.Insert(x);
	ls.Print();
	x = 35;
	if(ls.Search(x) == Success) cout << "Found " << x << endl;
	else cout << "Not Found " << x << endl;
	return 0;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

ListSet_对半搜索的迭代算法

标签:

原文地址:http://blog.csdn.net/gkhack/article/details/49639761

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!