基数排序-

#include "stdafx.h"
#include<iostream>
using namespace std;
//是权位数列,B是输出数列,D是原数列,k是范围
void COUNTING_SORT(int A[], int B[],int D[], int k)
{
	int C[10];
	for (int i = 0; i <= k; i++)
		C[i] = 0;
	for (int j = 0; j < 10; j++)
		C[A[j] - 1] += 1;
	for (int i = 1; i <= k; i++)
		C[i] = C[i] + C[i - 1];
	for (int i = 9; i >= 0; i--)
	{
		B[C[A[i] - 1] - 1] = D[i];
		C[A[i] - 1]--;
	}
}

void print(int a[], int k)
{
	for (int i = 0; i < k; i++)
		cout << a[i]<<" ";
	cout << "\n";
}

bool zero(int A[])
{
	for (int i = 0; i < 10; i++) {
		if (A[i] != 0)
			return false;
	}
	return true;
}


void weigh(int D[], int A[], int WEIGH)
{
	for (int j = 0; j < 10; j++) {
		A[j] = D[j] ;
	}
	for (int j = 0; j < 10; j++) {
		for (int i = 0; i < WEIGH; i++) {
			A[j] = A[j] / 10;
		}
	}
	if (!zero(A)) {
		for (int j = 0; j < 10; j++) {
			A[j] = A[j] % 10;
		}
	}
}



void radix(int D[], int B[], int k)
{
	int A[10];
	int WEIGH=0;
	weigh(D, A, WEIGH);
	while (!zero(A)) {
		COUNTING_SORT(A, B, D, 8);
		WEIGH++;
		weigh(D, A, WEIGH);
	}
}


int main()
{
	int D[] = { 4215,2526, 8732,6641, 5264 ,3288,2975, 1282 ,6596 ,7628 };
	int A[10];
	int B[10];
	print(D, 10);
	radix(D, B, 8);
	print(B, 10);
	while (1);
	return 0;
}

  

posted @ 2017-03-16 21:33  lineaar  阅读(132)  评论(0编辑  收藏  举报