Data structure: common sorting algorithm (7): radix sorting (C++ implementation)

Data structure: common sorting algorithm (7): radix sort

1. Basic idea:

Unify all values ​​to be compared (positive integers) to the same digit length, and padded zeros in front of the shorter digits. Then, starting from the lowest bit, sort one time in sequence. In this way, from the lowest order to the highest order, the sequence becomes an ordered sequence.

2. Examples

img

img

Example code:

#include<iostream>
using namespace std;
//辅助函数,求数据的最大位数
int maxbit(int data[], int n)
{
	int maxData = data[0];              ///< 最大数
	/// 先求出最大数,再求其位数,这样有原先依次每个数判断其位数,稍微优化点。
	for (int i = 1; i < n; ++i)
	{
		if (maxData < data[i])
			maxData = data[i];
	}
	int d = 1;
	int p = 10;
	while (maxData >= p)
	{
		//p *= 10; // Maybe overflow
		maxData /= 10;
		++d;
	}
	return d;
}
//基数排序
void radixsort(int data[], int n) 
{
	int d = maxbit(data, n);
	int *tmp = new int[n];
	int *count = new int[10]; //计数器
	int i, j, k;
	int radix = 1;
	for (i = 1; i <= d; i++) //进行d次排序
	{
		for (j = 0; j < 10; j++)
			count[j] = 0; //每次分配前清空计数器
		for (j = 0; j < n; j++)
		{
			k = (data[j] / radix) % 10; //统计每个桶中的记录数
			count[k]++;
		}
		for (j = 1; j < 10; j++)
			count[j] = count[j - 1] + count[j]; //将tmp中的位置依次分配给每个桶
		for (j = n - 1; j >= 0; j--) //将所有桶中记录依次收集到tmp中
		{
			k = (data[j] / radix) % 10;
			tmp[count[k] - 1] = data[j];
			count[k]--;
		}
		for (j = 0; j < n; j++) //将临时数组的内容复制到data中
			data[j] = tmp[j];
		radix = radix * 10;
	}
	delete[]tmp;
	delete[]count;
}
//打印数组
void print_arr(int data[],int n)
{
	for (int i = 0; i < n; i++)
	{
		cout<< data[i] << " ";
	}
	cout << endl;
}
//主函数
int main()
{
	int a[12] = { 27, 91, 1, 97, 17, 23, 84, 28, 72, 5, 67, 25 };
	cout << "排序前数组为:";
	print_arr(a, 12);
	radixsort(a, 12);
	cout << "排序后数组为:";
	print_arr(a, 12);
	return 0;
}

3. Summary:

Time complexity: Given n d digits (that is, d key codes, the value range of the key code is r), and the radix sort needs to compare each bit of the element, the complexity is O(d(n+r) ), the time complexity of one round of cyclic allocation is O(n), and the time complexity of one round of cyclic collection is O®, a total of d cycles are required for allocation and collection, that is, the time complexity is O(d(n+r) )

Guess you like

Origin blog.csdn.net/qq_43801020/article/details/108139874
Recommended