数据结构-排序-基数排序(c++实现)

#include<iostream>
using namespace std;
int GetMax(int a[],int n) {
	int max = a[0];
	for (int i = 1; i < n; i++) {
		if (a[i] > max)
			max = a[i];
	}
	return max;
}

void CountSort(int a[],int n,int exp) {
	int* tmp = new int[n];
	int buckets[10] = { 0 };

	for (int i = 0; i < n; i++) {
		buckets[(a[i] / exp) % 10]++;
	}
	for (int i = 1; i < 10; i++) {
		buckets[i] += buckets[i - 1];
	}
	for (int i = n - 1; i >= 0; i--) {
		tmp[buckets[a[i] / exp % 10] - 1] = a[i];
		buckets[a[i] / exp % 10]--;
	}
	for (int i = 0; i < n; i++) {
		a[i] = tmp[i];
	}
}

void RadixSort(int a[],int n) {
	int exp;
	int max = GetMax(a, n);

	for (exp = 1; max / exp > 0; exp = exp * 10) {
		CountSort(a, n, exp);
	}
}
int main() {
	int a[] = { 53, 3, 542, 748, 14, 214, 154, 63, 616 };
	int len = 9;
	RadixSort(a, len);
	for (int c : a) {
		cout << c << " ";
	}

}

猜你喜欢

转载自blog.csdn.net/qq_43710881/article/details/105894818
今日推荐