排序算法:9.基數排序

 

#include<iostream>
using namespace std;
#include<stdio.h>
#include<stack>
#include<list>
#include<assert.h>
#define BUFFER_SIZE 256
//排序之基數排序(先分散,再收集)
list<int>lst[10];
void distribute(int a[], int n, int k)
{
	int tmp;
	int x;
	for (int i = 0; i < n; ++i)
	{
		x = k;
		tmp = a[i];
		while (tmp&&x > 0)
		{
			tmp /= 10;
			x--;
		}
		lst[tmp % 10].push_back(a[i]);
	}
}
void collect(int a[])
{
	int k = 0;
	for (int i = 0; i < 10; ++i)
	{
		while (!lst[i].empty())
		{
			a[k++] = lst[i].front();
			lst[i].pop_front();
		}

	}
}
void radixsort(int a[], int n)
{
	for (int i = 0; i < 3; ++i)
	{
		distribute(a, n, i);
		collect(a);
	}
}
void  main()
{
	int a[] = { 16,25,12,30,47,11, 23,36,9,18,31};

	int n = sizeof(a) / sizeof(a[0]);
	radixsort(a, n);
	for (int i = 0; i < n; ++i)
	{
		cout << a[i] << " " << endl;
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章