Sorting algorithm (vii) Non-comparison sort: count sort, cardinal sort, bucket sort

Source: Internet
Author: User

The preceding is the comparison sorting algorithm, mainly bubble sort , select Sort , insert sort , merge sort , heap sort , quick Sort etc.

Non-comparison sorting algorithm: counting sort , Cardinal sort , bucket sort . Under certain conditions, their time complexity can reach O (n).

One, counting sort (counting sort) (1) Introduction to Algorithms

The Count sort (counting sort) is a stable sorting algorithm. The count sort uses an extra array of C, where the I element is the number of elements in the array A to be sorted with the value equal to I. The elements in a are then ranked in the correct position according to the array C. It can only sort integers.

(2) algorithm description and implementation
    1. Get the range of the number to be sorted (the upper and lower bounds are added here);
    2. The number of occurrences of each element in the statistic array that is I, in the array C;
    3. For all count additions (starting with the first element in C, each item and the previous item are added), the end position of each element in the sorted array is computed;
    4. Reverse-Populate the target array: Place each element I in the C (i) of the new array, subtract C (i) by 1 for each element placed

Realize

1  Public Static voidCountsort (int[] Array,intDownbound,intupperbound) {  2     int[] Countarray =New int[Upperbound-downbound + 1]; 3     if(Upperbound <downbound)4         return; 5      for(inti = 0; i < Array.Length; i++) {  6Countarray[array[i]-downbound]++; 7     }  8     intPosSum = 0; 9      for(inti = 0; I < Upperbound-downbound + 1; i++) {  TenPosSum + =Countarray[i];  OneCountarray[i] =PosSum;  A     }   -     int[] result =New int[Array.Length];  -      for(inti = array.length-1; I >= 0; i--) {   theResult[countarray[array[i]-Downbound]-1] =Array[i];  -Countarray[array[i]-downbound]--;  -     }   -      for(inti = 0; i < Array.Length; i++) {   +Array[i] =Result[i];  -     }   +}
(3) algorithm analysis

When the input element is an integer of n 0 to K, its run time is O (n + k). The count sort is not a comparison sort, and the sort is faster than any comparison sort algorithm. Since the length of the array C used to count depends on the range of data in the array to be sorted (equal to the difference between the maximum and minimum values of the array to be sorted plus 1), this makes the count sort for arrays with a large data range, which requires a lot of time and memory (if the data is scattered, there are actually a large number of 0 in Occupy a lot of space).

Best case: T (n) = O (n+k)
Worst case: T (n) = O (n+k)
Average condition: T (n) = O (n+k)

Two, bucket sort (bucket sort)

Bucket sorting is an upgraded version of the Count sort. It takes advantage of the mapping of functions, the key to efficiency is the determination of this mapping function.

(1) Introduction to Algorithms

Bucket sorting (bucket sort) works by assuming that the input data is uniformly distributed, that the data is divided into a limited number of buckets, and that each bucket is sorted separately (it is possible to use a different sorting algorithm or recursively continue to sort by the bucket.)

(2) algorithm description and implementation
    1. Set a quantitative array as an empty bucket;
    2. Traverse the input data, and put the data into the corresponding bucket one by one;
    3. Sort each bucket that is not empty;
    4. From a bucket that is not empty, stitch up the sorted data.

Realize

1  Public Static voidBucketsort (int[] arr) {  2       3     intMax =Integer.min_value; 4     intMin =Integer.max_value; 5      for(inti = 0; i < arr.length; i++){  6Max =Math.max (Max, arr[i]); 7Min =math.min (min, arr[i]); 8     }  9       Ten     //Number of barrels One     intBucketnum = (max-min)/Arr.length + 1;  AArraylist<arraylist<integer>> Bucketarr =NewArraylist<>(Bucketnum);  -      for(inti = 0; i < Bucketnum; i++){   -Bucketarr.add (NewArraylist<integer>());  the     }   -        -     //put each element into a bucket -      for(inti = 0; i < arr.length; i++){   +         intnum = (arr[i]-min)/(arr.length);  - bucketarr.get (num). Add (Arr[i]);  +     }   A        at     //sort each bucket -      for(inti = 0; I < bucketarr.size (); i++){   - Collections.sort (Bucketarr.get (i));  -     }   -}

A simple demonstration process for bucket sequencing of {29, 25, 3, 49, 9, 37, 21, 43} is given

(3) algorithm analysis

Bucket sorting is best used with linear time O (n), and the time complexity of bucket sequencing depends on the time complexity of sorting the data between buckets, because the time complexity of the other parts is O (n). Obviously, the smaller the bucket, the less data between buckets, and the less time it takes to sort. But the corresponding space consumption will increase.

Best case: T (n) = O (n+k)
Worst case: T (n) = O (n+k)
Average condition: T (n) = O (n2)

Three, Cardinal sort (Radix sort) (1) Introduction to Algorithms

The cardinality sort is sorted by the low, then collected (that is, sorted by the low), sorted by high order, then collected, and so on, until the highest bit. Sometimes some properties are prioritized, sorted by low priority, and sorted by high priority. The final order is high priority high in front, high priority is the same low priority high in front. The cardinality sort is based on sorting separately and is collected separately, so it is stable.

(2) algorithm description and implementation
    1. Gets the maximum number in the array and obtains the number of digits;
    2. Arr is the original array, starting from the lowest bit to take each bit to make up the radix array;
    3. The radix is counted (the use of the counting sort applies to the characteristics of the small range number);
1  Public Static voidRadixsort (int[] Array,intmaxdigit) {  2     intLen =Array.Length; 3     intDigitcount = 1; 4     intDigitdev = 1; 5     int[] tmp =New int[Len]; 6     int[] Count =New int[10]; 7      while(Digitcount <=maxdigit) {  8Arrays.fill (count, 0); 9Arrays.fill (count, 0); Ten          for(inti = 0; i < Len; i++) {   Onecount[(Array[i]/digitdev)% 10]++;  A         }   -         intsum = 0;  -          for(inti = 1; I < 10; i++) {   theCount[i] = Count[i] + count[i-1];  -         }   -          for(inti = len-1; I >= 0; i--) {   -tmp[count[(Array[i]/Digitdev)% 10]-1] =Array[i];  +count[(Array[i]/digitdev)% 10]--;  -         }   +          for(inti = 0; i < Len; i++) {   AArray[i] =Tmp[i];  at         }   -Digitdev *= 10;  -digitcount++;  -     }   -}

A simple demonstration process for cardinality ordering of {329, 457, 657, 839, 436, 720, 355} is given

(3) algorithm analysis

Best case: T (n) = O (n * k)
Worst case: T (n) = O (n * k)
Average condition: T (n) = O (n * k)

Cardinal Sort vs count sort vs bucket sort

These three sorting algorithms use the concept of buckets, but there are significant differences in how buckets are used:

Base sort: Allocates buckets based on each digit of the key value
Count Sort: Stores only a single key value per bucket
Bucket sort: Each bucket stores a range of values

Reference:

Http://www.cnblogs.com/eniac12/p/5332117.html

Https://www.cnblogs.com/jztan/p/5878630.html

http://blog.csdn.net/wangqyoho/article/details/52584640

Sorting algorithm (vii) Non-comparison sort: count sort, cardinal sort, bucket sort

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.