Simple implementation of three kinds of linear sorting algorithms (counting, cardinality, bucket sorting)

Source: Internet
Author: User

One, counting sort


A count sort assumes that each of the N input elements is an integer between 0 and K. Here k is an integer (the input data is within a small range).

Basic idea:

The basic idea of counting sorting is to determine the number of elements less than x for each INPUT element x. The x is then placed directly in its position in the final output array.

As shown in the following:


Because there may be equal numbers in the array, you need to be aware of the processing.

Time complexity and spatial complexity analysis algorithm total time θ (k + N). When K=o (n), the run time of the count sort is θ (n).

The spatial complexity is O (n+k). Requires two auxiliary arrays: the array that holds the sort results b[n], which holds the temporary results of the c[k].

Count ordering is a stable sorting algorithm: Elements with the same value in the output array are relative in the same order as they are in the input array.

Code implementation:

#include <iostream> #include <vector>using namespace std;void countsort (vector<int> &nums, Vector<int> &result) {int len = nums.size (); if (len = = 0) Return;int maxnum = int_min;for (int i = 0; i < Len; i++) Maxnum = max (Maxnum, nums[i]);//Find the maximum value to determine the size of the auxiliary array vector<int> tmp (maxnum+1, 0);//apply auxiliary array, note to +1, Because the subscript of the largest number corresponds to the maxnum (note: Here the maxnum is above k) for (int i = 0; i < len; i++) tmp[nums[i]]++;//counts the number of occurrences of each number for (int i = 1; I <= m Axnum; i++) {Tmp[i] + = tmp[i-1];//Multiply the number of occurrences}for (int i = len-1; I >= 0; i--) {Result[tmp[nums[i]]-1] = nums[i];//There is a-1 because result is starting from 0, different from the book tmp[nums[i]]--;}} int main () {int data[] = {2,5,3,0,2,3,0,3};//int data[] = {2,3,7,1,9,4,4,4,6,0};int len = sizeof (data)/sizeof (int); vector <int> nums (data, Data+len);vector<int> result (len, 0);cout<< "array before sorting is:"; for (int i = 0; i < Len; i+ +) cout<<nums[i]<< ""; Cout<<endl;countsort (nums, result);cout<< "sorted array is:"; for (int i = 0; i < Len; i++) cout<<result[i]<< ""; Cout<<endl;return 0;} 

Program execution Results:
[Email protected] cctmp]#./a.out the array before sorting is: 2 5 3 0 2 3 0 3 sorted array: 0 0 2 2 3 3 3 5 [[email protected] cctmp]#
Basic idea of cardinal rank:

A cardinal sort is a sequence of all the numbers from low to high. If all the highest digits are D, then the lowest significant digits are sorted first to get a result. Then repeat the process toward the high.

Sorting process:


It is important to note that the bitwise sort must be a stable sorting algorithm. Always use the above count sort.

The analysis of time complexity and spatial complexity

Given n-d digits, the number of possible values for each digit is k, if the stable bitwise sort time complexity used is θ (n+k), the cardinality sort time complexity is θ (d (n+k)). Space complexity O (n+k).

When D is constant,k=o (n), the cardinality sort has linear time complexity .

There is another theorem on how to decompose each keyword into several digits:

Given n b-dimensional numbers and any positive integer r<=b, the cardinality sort can sort the numbers in θ ((B/R) (n+2^r)) time.

Here, for a value of r<=b, each keyword is considered to have a D = floor (B/R) number, each number containing r bits, and then counting sort.

The above equation can be deduced to achieve the theta (n) complexity.

But this does not mean that the cardinality sort is better than a comparison-based sorting algorithm such as a fast row! Because the constant factor implied in the notation is different. Which sorting algorithm is better depends on the implementation characteristics of the underlying machine, such as the fast row with the = = row can often more effectively utilize the hardware cache. It also depends on the input data. and using the count sort as the intermediate stable sort is not sorted in situ.


Code implementation:
#include <iostream> #include <vector>using namespace std;//the maximum number of digits int maxbit (vector<int> &nums {int len = nums.size (), if (len = = 0) return 0;int maxnum = nums[0];for (int i = 1; i < Len; i++) Maxnum = max (Maxnum, n Ums[i]); int d = 0;while (Maxnum > 0) {maxnum/= 10;++d;} return D;} void Radixsort (vector<int> &nums) {int d = maxbit (nums); int len = nums.size ();vector<int> tmp (len, 0); VEC Tor<int> count (0); int radix = 1, I, J, k;//from backward forward to each bit, use count sort for (i = 1; I <= D; i++) {count.assign (10, 0  )///Count 0 for (j = 0; J < Len; J + +) {k = (Nums[j]/radix)% 10;//k to Nums[j] The count of the number of digits count[k]++;//(j = 1; J < 10; J + +) Count[j] + = count[j-1];for (j = len-1; J >= 0; j--) {k = (Nums[j]/radix)% 10;tmp[count[k]-1] = nums[j];//differs from count in Here count[k]--;} for (j = 0; J < Len; j + +) Nums[j] = tmp[j];//update sorted array radix *= 10;}} int main () {int data[] = {17243,5,213,17312,11858,3098,13288};int len = sizeof (data)/sizeof (int); VECTOR&LT;INT&GT Nums (data, Data+len);cout<< "array before sorting is:"; for (int i = 0; i < len; i++) cout<<nums[i]<< ""; cout<<e Ndl;radixsort (nums);cout<< "sorted array is:"; for (int i = 0; i < len; i++) cout<<nums[i]<< "";cout<< Endl;return 0;}

Program execution Results:

[[email protected] cctmp]#./a.out the array before sorting is: 17243   5       213 17312 11858   3098    13288 The sorted array is: 5       213     3098    11858   13288   17243   17312
Three, the basic idea of bucket sequencing:


Divides the interval [0,1] into n equal-sized sub-ranges, or buckets. The n input elements are then distributed across the buckets. The elements in each bucket are stored in a linked list.


In short, you put all the numbers in the corresponding Bucket_num buckets (/10), and each bucket maintains a list and sorts the linked list. Then merge these ordered lists.

Analysis of time and space complexity

The complexity of Time is O (n). The spatial complexity is O (n). A secondary array is required to hold the bucket (linked list).

Even if the input does not satisfy the uniform distribution, the bucket sort can still be run in linear time, as long as the input satisfies one of the conditions: the sum of squares of each bucket size is linearly related to the total element. Bucket sequencing is a stable sorting algorithm.

Code implementation:

#include <iostream> #include <vector> #include <time.h>using namespace std;const int bucket_num = 10;// The number of buckets const int num_size = 20;//number number//Bucket list node struct listnode{int mdata; ListNode *mnext; ListNode () {}listnode (int data): Mdata (data), Mnext (NULL) {}}; ListNode *insert (ListNode *, int);//Insert points into the list ListNode *merge (ListNode *, ListNode *);//merge two ordered linked lists//bucket sorting algorithm void Bucketsort ( Vector<int> &nums) {ListNode *buckets[bucket_num] = {null};//build bucket_num buckets (array of pointers, each element within the array is a pointer to the linked list) int Len = Nums.size (); if (len = = 0) return;for (int i = 0; i < len; i++) {int index = nums[i]/bucket_num;//Find out which bucket the number is inserted into. List Node *head = buckets[index];//Gets the head node of the bucket Buckets[index] = insert (head, nums[i]);//Insert the number into the bucket}//merge all the buckets (the numbers in the bucket are ordered) ListNode *head = buckets[0];for (int i = 1; i < Bucket_num; i++) {head = Merge (head, buckets[i]);} Assigns the ordinal number to the array for (int i = 0; i < len; i++) {Nums[i] = Head->mdata;head = Head->mnext;}} Insert the new node into the list in the appropriate position, so that the list is orderly (in fact, insert sort) ListNode *insert (ListNode *head, int val) {//If the list is empty, or VAL Smaller than the head node, then the new node as the head node if (head = = NULL | | val < head->mdata) {ListNode *newhead = new ListNode (val); newhead->mnext = Head ; head = Newhead;return head;} ListNode *pre = head, *cur = head->mnext; ListNode *newnode = new ListNode (val);//node where new node is to be inserted while (cur! = NULL && cur->mdata <= val) {pre = CUR;CU R = Cur->mnext;} Newnode->mnext = Cur;pre->mnext = Newnode;return head;} Merge two ordered linked lists ListNode *merge (ListNode *head1, ListNode *head2) {if (head1 = = null) return head2;if (head2 = null) return head1; ListNode Dummynode; ListNode *p = &dummyNode; ListNode *p1 = head1, *p2 = Head2;while (P1 && p2) {if (P1->mdata <= p2->mdata) {p->mnext = P1;P1 = P1-&G T;mnext;} Else{p->mnext = P2;P2 = P2->mnext;} p = p->mnext;} if (p1) P->mnext = p1;if (p2) p->mnext = P2;return Dummynode.mnext;} int main () {Srand ((unsigned) time (NULL));vector<int> nums;for (int i = 0; i < num_size; i++) {int NUM = rand ()% 10 0;//here take each number <100nums.push_back (num);} cout<<"The array before sorting is:"; for (int i = 0; i < num_size; i++) cout<<nums[i]<< ""; Cout<<endl;bucketsort (nums);cout<< "The sorted array is:"; for (int i = 0; i < num_size; i++) cout<<nums[i]<< ""; Cout<<endl;return 0;}

Program execution Results:



Copyright NOTICE: Reprint please indicate the source.

Simple implementation of three kinds of linear sorting algorithms (counting, cardinality, bucket sorting)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.