桶排序——C++实现

桶排序——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());
	/*int a = 10;
	int* ptr = &a;
	int b = *ptr;
	b = 100;
	cout << "*ptr: " << *ptr << endl;*/

	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)
{
	//typedef decltype(*begin) item_type;
	printList(begin, end);

	//item_type max_item = *begin;
	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]();   // 构造一个排序用的“桶” 0 - max_item + end位。
	auto tmp_bucket_list_ptr = bucket_list_ptr;

	printList(bucket_list_ptr, bucket_list_ptr + max_item + 1);  // bucket_list_ptr + max_item + 1 = end位

	printList(begin, end);

	for (Iterator i = begin; i != end; i++) {
		/*cout << "*i: " << *i << endl;*/
		*(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++;	
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值