Introduction
The cardinality sort (ascending) is a non-comparative sort, with the quick rows, the bubbling sort, the insertion sort, and the sort algorithms that were mentioned in the previous blog post, which do not use any of the methods of swapping, and then what is the sort of order? Its basic idea is to allocate the elements from small to large by assigning them to the function of sorting. Algorithm Description
1. Create 10 barrels, respectively, to put the corresponding numbers;
2. According to the lowest digit (digit) of the number assigned to the corresponding bucket inside;
3. Put the numbers in the bucket back into the array in turn;
4. According to the sub-low number assigned to the corresponding bucket inside;
5. Put the numbers in the bucket back into the array in turn;
6. Repeat the above work until every bit of each number is accessed. complexity of Time:
Bucket sequencing is a very efficient sorting algorithm, time complexity is O (N), many times faster than fast, and the bucket is very stable, the only disadvantage is that his spatial complexity is higher than the other sorts. as shown in Figure
For single-digit distribution
assigning to 10-bit
Assign to the Hundred
Code Implementation
#include <iostream> #include <list> using namespace std;
int Getmax (int* arr, int size) {//calculates the maximum number of digits int n = 1;
int base = 10;
for (int i = 0, i < size; ++i) {while (Arr[i] >= base) {n++;
Base *= 10;
}} return n;
} void Bucketsort (list<int>* l,int* A, int size) {int i = 0;
int index = 0;
int n = Getmax (A, size);
int x = 1;
while (n--) {for (i = 0; i < size; ++i) {//allocated to the bucket index = a[i]/x% 10;
L[index].push_back (A[i]);
} int j = 0;
int k = 0; for (j = 0; J < ++j) {//Put back array while (!l[j].empty ()) {a[k++] = L[j].
Front ();
L[j].pop_front ();
}} x *= 10;
}} int main () {list<int> l[10];//uses the list array to act as the bucket's function int a[10] = {12,45,13,65,85,111,23,15,17,56}; int len = sizeof (a)/SizeoF (a[0]);
Bucketsort (L, a, Len);
for (int i = 0; i < len; i++) {cout << a[i] << "";
} return 0; }