Sorting Algorithm - counting sequencing

The basic idea

Counting sort is a linear sorting algorithm, which uses an array, the array because the next target growth is linear, so it put his element converted to open up a new array subscript. But the index is non-negative ah? An array of values ​​among the positive and negative ah. A simple conversion to make the line: find the smallest element in the array, the value is subtracted from the element, so that all the elements of the corresponding index to find out. (Actually feels like a mapping function?) Saved in the following figure is to be sorted array: [- 1, -5, -6, -2,1,2,8,2,1,8]

 Then with the idea of ​​ordering a hash of the same: here. Direct open up a corresponding hash array, and then count the number of times each element appears. Orange marked out to be sorted array represents no elements (elements after conversion), there is no natural occurrences. This can be seen if the array elements in a large gap, but it is still a waste of space, because it opened up a new array size is to be sorted array arr in max-min + 1 (8 + 6 + 1 = 15).

 

Then the final count of elements arr put back in to complete the sort.

Algorithm code

 1 //计数排序
 2 void CountSort(int *a, int size)
 3 {
 4     int max = a[0];
 5     int min = a[0];
 6     for (int i = 0; i < size; ++i)
 7     {
 8         if (a[i] > max)
 9             max = a[i];
10         if (a[i] < min)
11             min = a[i];
12     }
13 is      int Range = max - min + . 1 ; // to open up the range of the array 
14      int * COUNT = new new  int [Range];
 15      Memset (COUNT, 0 , the sizeof ( int ) * Range); // initializes to 0
 16                                             / / number statistics for each number appears 
. 17      for ( int I = 0 ; I <size; I ++)            // fetch from the original array, the number of the original array of size 
18 is      {
 . 19          COUNT [a [I] - min ] ++ ;
 20      }
 21      // written back to the original array 
22     int index = 0 ;
 23 is      for ( int I = 0 ; I <Range; I ++) // read from the array opens, the array size is open Range 
24      {
 25          the while (COUNT [I] - )
 26 is          {
 27              A [index ++] = + I min;
 28          }
 29      }
 30      Delete [] COUNT;
 31 is }

 Analysis of Algorithms

Counting sequencing is a non-comparison-based sorting algorithm, spatial complexity and are time complexity O (n + k), where k is an integer in the range.


[Reference: https: //blog.csdn.net/qq_34269988/article/details/90705977]

Guess you like

Origin www.cnblogs.com/WindSun/p/11361008.html
Recommended