桶排序——C++实现
template_head.h
#include <iostream>
#include <vector>
#include "../head_file/template_head.h"
using namespace std;
void bucket_sort()
{
cout << "Bucket Sort!!!" << endl;
vector<int> list = { 8,9,1,7,2,3,5,4,6,0,15,9,8 };
bucketSort(list.begin(), list.end());
printList(list);
}
template <typename Iterator>
void bucketSort(const Iterator& begin, const Iterator& end)
{
bucketSort(begin, end, less_<decltype(*begin)>{});
}
template <typename Iterator, typename Comparator>
void bucketSort(const Iterator& begin, const Iterator& end, Comparator lessThan)
{
printList(begin, end);
int max_item = *begin;
cout << "type of max_item: " << typeid(max_item).name() << endl;
cout << "type of beign: " << typeid(begin).name() << endl;
for (Iterator i = begin; i != end; i++) {
if (max_item < *i) {
cout << "*begin: " << *begin << " *i: " << *i << endl;
max_item = *i;
}
}
cout << "max_item: " << max_item << " *begin: " << *begin << endl;
printList(begin, end);
auto bucket_list_ptr = new int[max_item + 1 + 1]();
auto tmp_bucket_list_ptr = bucket_list_ptr;
printList(bucket_list_ptr, bucket_list_ptr + max_item + 1);
printList(begin, end);
for (Iterator i = begin; i != end; i++) {
*(tmp_bucket_list_ptr + *i) += 1;
}
printList(bucket_list_ptr, bucket_list_ptr + max_item + 1);
tmp_bucket_list_ptr = bucket_list_ptr;
Iterator i = begin;
while (tmp_bucket_list_ptr < bucket_list_ptr + max_item + 1)
{
while (*tmp_bucket_list_ptr > 0)
{
*i = tmp_bucket_list_ptr - bucket_list_ptr;
i++;
*tmp_bucket_list_ptr -= 1;
}
tmp_bucket_list_ptr++;
}
}