多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
递归函数效率低, 常使用相应的迭代算法. 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; } ~~~