桶排序

#include <iostream>
using namespace std;

class listnode
{
public:
	int elem;
	listnode* next;

	listnode()
	{
		next = 0;
	}
};

class list
{
public:
	listnode* head;

	list()
	{
		head = NULL;
	}

	~list()
	{
		listnode* t = head;
		while (t != 0)
		{
			listnode* tmp = t;
			t = t->next;
			delete tmp;
		}
	}

	void insertElem(int elem)
	{
		listnode* node = new listnode();
		node->elem = elem;
		node->next = 0;
		
		if (head == NULL)
		{
			head = node;
		}
		else
		{
			if (node->elem < head->elem)
			{
				node->next = head;
				head = node;
			}
			else
			{
				listnode* prev = head;
				listnode* t = head->next;
				while (t != 0)
				{
					if (node->elem < t->elem)
					{
						prev->next = node;
						node->next = t;
						return ;
					}
					prev = t;
					t = t->next;
				}

				prev->next = node;
			}
		}
	}

	void print_list()
	{
		listnode* t = head;
		while (t)
		{
			cout << t->elem << " ";
			t = t->next;
		}
		cout << endl;
	}
};


void print_array(int* array, int size)
{
	for (int i=0; i<size;  i++)
		cout << array[i] << " ";
	
	cout << endl;
}

void bucket_sort(int* array, int size)
{
	list* buckets = new list[10]; //假设分成10个区间
	for (int i=0; i<10; i++)
		buckets[i].head = NULL;

	for (int i=0; i<size; i++)
	{
		int which_bucket = array[i] / 100;
		buckets[which_bucket].insertElem(array[i]);
	}

	int m = 0;
	for (int i=0; i<10; i++)
	{
		// copy back
		listnode* t = buckets[i].head;
		while (t != 0)
		{
			array[m] = t->elem;
			t = t->next;
			m++;
		}
	}

	delete[] buckets;
}

void main()
{
	int* array = 0;
	int size;
	cout << "input the size:";
	cin >> size;

	array = new int[size];
	for (int i=0; i<size; i++)
	{
		array[i] = rand()%1000;
	}

	print_array(array, size);
	bucket_sort(array, size);
	print_array(array, size);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值