鄙人最近想重拾C++,所以准备写一些小程序,今天呢上一个最简单的冒泡排序的模板类。菜鸟领地,埋有地雷,高手请绕行。
这个程序就没有什么说的了,冒泡排序的时间代价也是 n² 相关,不过容易实现,如果在急需排序却又想不起更有效的排序方法的时候,这个可以拿来用一下。
需要注意的一个地方是程序没有异常处理,如果是通过只传递Type *的构造函数的话可能会出现数组越界的危险。
sort.h代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | #ifndef SORTSUB_H_ #define SORTSUB_H_ #include <iostream> template <class Type> class SortSub { private: Type * m_head; int m_length; bool m_detect; protected: void getItems(); int calLength(const Type*)const; void sort(); public: SortSub(); SortSub(const Type*, const int); SortSub(const Type*); ~SortSub(); int getLength()const{ return this->m_length; } Type * getHead()const{ return this->m_head; } void show(); }; template <class Type> void SortSub<Type>::getItems() { using namespace std; m_length = 0; m_head = 0; cout <<"Enter the length of your numbers: "; while(!(cin >>m_length) || m_length<0 || cin.get()!='\n') { cerr <<"Enter error.Do it again: "; cin.clear(); while(cin.get()!='\n') continue; } m_head = new Type[m_length+1]; for(int i=0; i<m_length; i++) m_head[i] = 0; m_head[m_length] = '\0'; for(int j=0; j<m_length; j++) { cout <<"\tEnter #"<<j+1<<" number: "; while(!(cin >>m_head[j]) || cin.get()!='\n') { cerr <<"\nEnter error.Do it again: "; cin.clear(); while(cin.get()!='\n') continue; } } sort(); } template <class Type> int SortSub<Type>::calLength(const Type* head)const { int count = 0; if(head != 0) while(head[count] != '\0') count++; return count; } template <class Type> void SortSub<Type>::sort() { Type * head = getHead(); int counts = getLength(); for(int i=counts-1; i>0; i--) for(int j=0; j<i; j++) { if(head[j]>head[j+1]) { head[j+1] += head[j]; head[j] = head[j+1] - head[j]; head[j+1] -= head[j]; } } } template <class Type> SortSub<Type>::SortSub() { getItems(); m_detect = true; } template <class Type> SortSub<Type>::SortSub(const Type* head,const int size) { m_head = head; m_length = size; m_detect = false; sort(); } template <class Type> SortSub<Type>::SortSub(const Type* head) { m_head = head; m_length = calLength(head); m_detect = false; sort(); } template <class Type> SortSub<Type>::~SortSub() { if(m_detect) delete [] m_head; } template <class Type> void SortSub<Type>::show() { using std::cout; Type * head = getHead(); cout <<"\tThet ordered numbers are: \n\t"; for(int i=0; i<getLength(); i++) cout<<head[i]<<" "; cout <<"\n"; } #endif |
声明:本文采用 BY-NC-SA 协议进行授权 | 星期九
原创文章转载请注明:转自《C++模板类冒泡排序》
嗯,我的计划之内的事情。可惜现在做不了。
@Kada, 最近在忙啥呢?