c++ 基数排序算法

Radix Sort Algorithm is a unique sorting algorithm that works on the basic principle of numbers being an ensemble of digits. Radix Sort works only on integer values since integers have only a single mathematical component, digits.

基数排序算法是一种独特的排序算法,它根据数字是一组数字的基本原理进行工作。 “基数排序”仅适用于整数值,因为整数只有一个数学成分,即数字。

In this sorting algorithm, the numbers are initially arranged according to their least significant digit, moving onto their most significant digit, while maintaining the previous order.

在这种排序算法中,数字最初是根据其最低有效位排列的,然后移至其最高有效位,同时保持先前的顺序。



基数排序算法如何工作? (How Does the Radix Sort Algorithm Work?)

Let us quickly jump to the details of the algorithm, with an example running side by side.

让我们快速并肩并举一个例子,快速了解算法的细节。

Radix Sort Input Array
Input Array
输入数组

步骤1:找出最大元素 (Step 1: Finding the maximum element)

As we previously mentioned, the algorithm arranges numbers using the least significant digit to the most significant digit, therefore we need to know the range of these iterations. For this purpose, we need to find the maximum element.

如前所述,该算法使用最低有效位到最高有效位来排列数字,因此我们需要知道这些迭代的范围。 为此,我们需要找到最大元素。

Radix Sort Max Element
Maximum element in the array
数组中的最大元素

After finding the maximum number, we need to count its digits.

找到最大数量后,我们需要计算其位数。



步骤2:计算最大位数的位数 (Step 2: Count the number of digits of the maximum number)

We need to know the number of times we have to arrange the array, therefore there is a necessity to count the number of digits.

我们需要知道必须安排数组的次数,因此有必要计算数字的位数。

Radix Sort No Of Digits
Number of digits of maximum element
最大元素的位数

As we can see, the maximum element has three digits, therefore the arrangement will be done thrice.

如我们所见,最大元素有三位数,因此排列将进行三次。



步骤3:根据最低有效数字排列数字 (Step 3: Arrange the numbers on the basis of the least significant digit)

The initial arrangement of sorting requires us to sort the elements on the basis of their least significant digit.

排序的初始安排要求我们根据元素的最低有效位数对其进行排序。

Radix Sort Lsd Edited
Arranging numbers using units place digit
使用单位放置数字排列数字

The key point to note here is that, numbers having different units place, but identical digits in other positions are mutually arranged in the right way.

这里要注意的关键点是,具有不同单位的数字位置不同,但是其他位置的相同数字以正确的方式相互排列。

For instance, the number 36 at index 3, and the number 32 at index 7, have a different digit in the units place, but other digits are identical. Initially, 32 is after 36 in the array, but after arranging the numbers according to units place, 32 comes before 36.

例如,索引3处的数字36和索引7处的数字32在单位位置具有不同的数字,但其他数字相同。 最初,32在数组中的36之后,但是在根据单位位置排列数字之后,32在36之前。



步骤4:根据下一个有效数字排列数字 (Step 4: Arrange the numbers according to the next significant digit)

Keeping the current arrangement intact, we will try to arrange the numbers on the basis of tens place.

在保持当前排列不变的情况下,我们将尝试在十位的基础上排列数字。

For this purpose, we will need a stable sort while implementation. Stable sorting algorithms are those, which preserves the initial arrangement of equal numbers.

为此,我们将需要在执行过程中进行稳定的排序。 稳定的排序算法是这样的算法,可以保留相等数量的初始排列。

Radix Sort Tens Digit Edited
Arranging numbers using tens place digit
使用十位数字排列数字

After the sorting based on tens place digit is completed, we can notice that all the numbers below 100, are arranged properly among themselves.

在完成基于十位数字的排序后,我们可以注意到所有低于100的数字在它们之间都是正确排列的。

Basically, if an array contains numbers below 100, only two iterations of arranging will sort the complete array.

基本上,如果数组包含的数字小于100,则仅两次迭代即可对整个数组进行排序。

Note: The numbers below 10, (having no tens place digit), are considered to have a tens place digit as 0. It makes sense, as they are to be placed before numbers having a tens place digit as 1.

注意:小于10的数字(无十位数字)被视为十位数字为0。这是有意义的,因为将它们放置在十位数字为1的数字之前。



步骤5:继续执行该过程,直到最高位 (Step 5: Keep performing the process until the most significant digit)

In this example, the most significant digit is hundred place digit. Therefore this is the last step of the Radix Sort Algorithm.

在此示例中,最高有效位是百位数字。 因此,这是基数排序算法的最后一步。

Radix Sort Hundreds Digit Edited
Arranging numbers using hundreds place digit
使用数百位数字排列数字

As we can see, the array is now completely sorted. This is happens as soon as the array is arranged according to the most significant digit.

如我们所见,该数组现在已完全排序。 只要按照最高有效位排列数组,就会发生这种情况。

Before moving onto the implementation of Radix Sort, we will recommend you to study the concepts of Counting Sort Algorithm, which is used as a sub-routine for sorting the numbers based on individual digits.

在继续介绍Radix Sort的实现之前,我们建议您研究Counting Sort Algorithm的概念,该算法用作子例程,用于根据单个数字对数字进行排序。



基数排序算法在C ++中的实现 (Implementation of Radix Sort Algorithm in C++)


#include<bits/stdc++.h>
using namespace std;

// Function that performs Radix Sort
void radix_sort(int arr[], int n){

	// Step 1: Find the maxumum element
	int maximum = arr[0];

	for(int i=1;i<n;i++){
		maximum = max(maximum, arr[i]);
	}

	// Step 2: Count the number of digits of the maximum number
	int digits = 0;

	while(maximum > 0){
		digits++;
		maximum /= 10;
	}

	// Step 3, 4, 5: Arrange the numbers on the basis of digits
	for(int i=0;i<digits;i++){

		// Units/Tens/Hundreds - used to determine which digit
		int power = pow(10, i);

		// Holds the updated array 
		int new_array[n];

		// Counting Sort Array - required for arranging digits [0-9]
		int count[10];

		// Initializing Count Array
		memset(count, 0, sizeof(count));

		// Calculating frequency of digits
		for(int j=0;j<n;j++){

			// The digit under consideration in this iteration
			int num = (arr[j]/power) % 10;

			count[num]++;
		}

		// Cumulative frequency of count array
		for(int j=1;j<10;j++){
			count[j] += count[j-1];
		}

		// Designating new positions in the updated array
		for(int j=n-1;j>=0;j--){

			// The digit under consideration in this iteration
			int num = (arr[j]/power) % 10;

			new_array[count[num]-1] = arr[j];
			count[num]--;
		}

		// Updating the original array using New Array
		for(int j=0;j<n;j++)
			arr[j] = new_array[j];
	
	}

	// Printing the sorted array
	for(int j=0;j<n;j++)
		cout<<arr[j]<<" ";

	cout<<endl;			
}

// The main function
int main(){

	// The array containing values to be sorted
	int arr[] = {15, 120, 53, 36, 167, 81, 75, 32, 9, 60};

	// Size of the array
	int n = sizeof(arr)/sizeof(n);

	// Function call for the Radix Sort Algorithm 
	radix_sort(arr, n);

	return 1;
}

OUTPUT:

输出:


9 15 32 36 53 60 75 81 120 167


C语言基数排序算法的实现 (Implementation of Radix Sort Algorithm in C)


#include<stdio.h>

// Function that performs Radix Sort
void radix_sort(int arr[], int n){

	// Step 1: Find the maxumum element
	int maximum = arr[0];

	for(int i=1;i<n;i++){
		if(maximum < arr[i])
			maximum = arr[i];
	}

	// Step 2: Count the number of digits of the maximum number
	int digits = 0;

	while(maximum > 0){
		digits++;
		maximum /= 10;
	}

	// Units/Tens/Hundreds - used to determine which digit
	int power = 1;

	// Step 3, 4, 5: Arrange the numbers on the basis of digits
	for(int i=0;i<digits;i++){

		// Holds the updated array 
		int new_array[n];

		// Counting Sort Array - required for arranging digits [0-9]
		int count[10];

		// Initializing Count Array
		for(int j=0;j<10;j++)
			count[j] = 0;

		// Calculating frequency of digits
		for(int j=0;j<n;j++){

			// The digit under consideration in this iteration
			int num = (arr[j]/power) % 10;

			count[num]++;
		}

		// Cumulative frequency of count array
		for(int j=1;j<10;j++){
			count[j] += count[j-1];
		}

		// Designating new positions in the updated array
		for(int j=n-1;j>=0;j--){

			// The digit under consideration in this iteration
			int num = (arr[j]/power) % 10;

			new_array[count[num]-1] = arr[j];
			count[num]--;
		}

		// Updating the original array using New Array
		for(int j=0;j<n;j++)
			arr[j] = new_array[j];
		
		// Updating the digit to be considered next iteration
		power *= 10;
	}

	// Printing the sorted array
	for(int j=0;j<n;j++)
		printf("%d ", arr[j]);
	printf("\n");			
}

// The main function
int main(){

	// The array containing values to be sorted
	int arr[] = {15, 120, 53, 36, 167, 81, 75, 32, 9, 60};

	// Size of the array
	int n = sizeof(arr)/sizeof(n);

	// Function call for the Radix Sort Algorithm 
	radix_sort(arr, n);

	return 1;
}

OUTPUT:

输出:


9 15 32 36 53 60 75 81 120 167


基数排序算法涉及的复杂性 (Complexities involved in Radix Sort Algorithm)

时间复杂度 (Time Complexity)

Let us study the time complexity of each step in the algorithm:

让我们研究算法中每个步骤的时间复杂度:

  • Step 1: To find the maximum element, we linearly traverse the entire array — O(n)

    第1步:要找到最大元素,我们线性遍历整个数组— O(n)
  • Step 2: If we consider 'd' as the number of digits in the maximum element, then the loop for calculating the number of digits will run 'd' times — O(d)

    步骤2:如果我们将'd'视为最大元素中的位数,则用于计算位数的循环将运行'd'O(d)
  • Step 3, 4, 5: These steps work on the same principle of arranging numbers on the basis of digits. These steps run for 'd' times, and every time a sub-routine of “Counting Sort” is implemented — O(d * n)

    步骤3、4、5:这些步骤的工作原理与以数字为基础的数字相同。 这些步骤运行'd'次,并且每次执行“计数排序”子例程O(d * n)

Total Time Complexity: O(d * n)

总时间复杂度: O(d * n)

Note: The loops running for Count Array does not amount to significant time complexity since a loop running for a said 10 times, is considered constant time usage.

注意:为Count Array运行的循环不会造成明显的时间复杂性,因为运行所述10次的循环被视为固定时间使用。



空间复杂度 (Space Complexity)

  • Step 1: We need a single variable to store the maximum element — O(1)

    步骤1:我们需要一个变量来存储最大元素— O(1)
  • Step 2: One variable store the number of digits — O(1)

    步骤2:一个变量存储位数O(1)
  • Step 3, 4, 5: Each iteration of “Counting Sort” requires us to create an array for storing newly arranged values — O(n).

    步骤3、4、5: “计数排序”的每次迭代都要求我们创建一个数组来存储新排列的值O(n)

Total Space Complexity: O(n)

总空间复杂度: O(n)



结论 (Conclusion)

For the past few decades, sorting techniques have been studied extensively by algorithmic experts. Radix Sort is one of the most unique non-comparative sorting algorithm.

在过去的几十年中,算法专家对排序技术进行了广泛的研究。 基数排序是最独特的非比较排序算法之一。

We hope that this article was easy to understand for beginners trying to learn various sorting techniques. Feel free to ping us below for further explanations or queries.

我们希望对于尝试学习各种排序技术的初学者来说,本文容易理解。 请随时在下面ping我们,以获取进一步的解释或疑问。

翻译自: https://www.journaldev.com/42955/radix-sort-algorithm

c++ 基数排序算法

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐