计数排序、基数排序、桶排序

#include 
#include 
#include 
#include 
#include 

using namespace std;

class MySort {
public:
	MySort(vector v):m_num(v) {}
	virtual ~MySort() = 0{}
	virtual void Sort() = 0;
	void display() {
		copy(m_num.begin(), m_num.end(), ostream_iterator(cout, " "));
		cout << endl;
	}
protected:
	vector m_num;
};

// 计数排序
class CountSort: public MySort {
public:
	CountSort(vector v):MySort(v) {}
	void Sort() {
		int len = m_num.size(), i;
		if (len < 2) return ;
		int iMax = *max_element(m_num.begin(), m_num.end());
		vector count(iMax+1, 0), container(len, 0);
		for (i = 0; i < len; ++ i)
			++ count[m_num[i]];
		for (i = 1; i <= iMax; ++ i)
			count[i] += count[i-1];
		for (i = len-1; i >= 0; -- i) {
			container[count[m_num[i]] - 1] = m_num[i];
			-- count[m_num[i]];
		}
		copy(container.begin(), container.end(), m_num.begin());
	}
};

// 基数排序
class RadixSort: public MySort {
public:
	RadixSort(vector v) : MySort(v) {}

	int getBitCount() {
		int iMax = *max_element(m_num.begin(), m_num.end());
		int d = 0;
		while (iMax) {
			++ d;
			iMax /= 10;
		}
		return d;
	}

	void Sort() {
		int len = m_num.size();
		if (len < 2) return ;
		int d = getBitCount(), i, j;
		int r = 1;
		vector count(10, 0),  container(len, 0);
		for (i = 0; i < d; ++ i) {
			container.assign(len, 0);
			count.assign(10, 0);
			for (j = 0; j < len; ++ j) {
				++ count[(m_num[j]/r) % 10];
			}

			for (j = 1; j < 10; ++ j) {
				count[j] += count[j-1]; 
			}
			
			for (j = len - 1; j >= 0; -- j) {
				int index = (m_num[j]/r) % 10;
				container[count[index] - 1] = m_num[j];
				-- count[index];
			}
			copy(container.begin(), container.end(), m_num.begin());
			r *= 10;
		}
	}
};

// 桶排序
class BucketSort: public MySort {
public:
	BucketSort(vector v):MySort(v){}

	void Sort() {
		int len = m_num.size();
		if (len < 1) return;
		list *lst = new list[len];
		int iMax = *max_element(m_num.begin(), m_num.end());
		int i, index;
		for (i = 0; i < len; ++ i) {
			index = (m_num[i] * len) / (iMax + 1);
			for (list::iterator it = lst[index].begin(); it != lst[index].end(); ++ it) {
				if (*it > m_num[i]) {
					lst[index].insert(it, m_num[i]);
					break;
				}
			}
			if (it == lst[index].end())
				lst[index].insert(it, m_num[i]);
		}

		index = 0;
		for (i = 0; i < len; ++ i) {
			copy(lst[i].begin(), lst[i].end(), m_num.begin() + index);
			index += lst[i].size();
		}
		delete [] lst;
	}
};

int main() {
	int ia[] = {49, 38, 65, 97, 76, 13, 27, 49, 132, 134};
	vector v(ia, ia+10);
	MySort *p;
        // p = new CountSort(v);
        // p = new RadixSort(v);
        p = new BucketSort(v);
	p->Sort();
	p->display();

	return 0;
}

你可能感兴趣的:(algorithm,c++,排序算法)