[Pratice]简单版桶排序

本文介绍了一种使用桶排序算法对数组元素进行计数并输出的方法,详细解释了如何获取数组中的最大值和最小值,确定桶的数量,并通过遍历数组将每个元素放入相应的桶中。接着,通过遍历桶来输出每个元素出现的次数,展示了桶排序在数据处理中的应用。


转自 http://ahalei.blog.51cto.com/4767671/1362789


#include <iostream>
#include <memory.h>
using namespace std;

//just demo, so there isn't more function
int main(int argc, char const *argv[])
{
	int value[] = {9, 1, 8, 3, 3, 4, 6};

	int min = value[0], max = value[0];
	for (int i = 0; i < 7; ++i)		//get the min and max
	{							   //to ensure the amount of buckets
		if(value[i] > max)
			max = value[i];

		if(value[i] < min)
			min = value[i];
	}

	int* p = new int[1 + max - min];
	if (p == NULL)	return 0;
	memset(p, 0, (1 + max - min) * sizeof(int));
	for (int i = 0; i < 7; ++i)		//throw in bucket
	{
		++p[value[i] - min];
	}
		
	for (int i = 0; i < 1 + max - min; ++i)		//get the result
	{
		if (p[i])
		{
			for (int j = 0; j < p[i]; ++j)
				cout << i+1 << " ";
		}
	}
	cout << endl;
	
	delete[] p;
	p = NULL;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值