Base sort _radixsort

Source: Internet
Author: User

    • Base sort _radixsort
      • The idea of Cardinal sort
      • Implementation of radix sorting algorithm
        • Base sort based on count sort
        • Base sorting based on optimal bucket ordering

Base sort _radixsort

A cardinal sort is a type based onCount Sort _countingsortor aOptimal bucket sequencing(It can also be based on other sorting algorithms, except that the counting sort should be the quickest for the cardinality sort, because both pinyin isjishupaixu, haha) one can be in linear time O ( n ) The sorting algorithm is completed. Bloggers in the base sort of homework, found that some of the blog is written in基数排序It is桶排序, I think that the cardinal sort and the bucket sort are different, although both use the idea of the bucket, but the things that they do in the bucket are completely dissimilar:

    • The base sort only borrows 10 buckets to sort the 10 cardinality of 0-9 (which can be said to be the optimal bucket sort), repeatedly in the stable case, on the bit, 10 bits ... Sort the buckets separately
    • And the bucket is not necessarily a bucket of 10 barrels, can be any number of barrels, just the number of barrels will affect the speed of sorting, bucket sorting is mainly to map the elements into the bucket, and then in the various barrels in the sorting, and finally the various barrels inside the array together (we will be in the later article Introduction bucket sort)

For a general sorting algorithm, the size order of the elements is determined by comparing the size of the elements to the elements, which at least cost the worst case o(nlOgn) However, this is not the case for the cardinality sort, which can be said to be a comparison between elements and elements in the cardinality order, which is accomplished by counting the number of elements in the array.

The idea of Cardinal sort

The idea of base sorting is actually very simple, that is, each number in the sequence is sorted by digit first, then the number is sorted by 10 bits, and so on, all the bits are sorted, then the last sequence is ordered.

question one : What if the number of digits is not the same length? For example, some numbers are up to 10 digits, some numbers are the largest

answer : The longest in the sequence of the benchmark, the number of bits is not enough to fill 0, such as the highest number of digits to hundreds, then the number 45 is 0 for 045

Question 2: Why not sort from a high point, but start with a single digit

answer : Because the higher the number, the higher the proportion of the possession, the order of the bit is to determine the sequence of the individual numbers in the same 10-digit case, and the 10-bit sort can directly ignore the sort of bits, and the 10-bit ordering is to determine the position of each number in the same situation as the hundred.

Suppose we have such a sequence:
913 75 794 629 48 375 958 630 190 632
Now we're going to sort it out in cardinal order

Step one : To complement each number
913 075 794 629 048 375 958 630 190 632

Step two : sort the digits
630 190 632 913 794 075 375 048 958 629

Step three : Sort the 10 bits
913 629 630 632 048 958 075 375 190 794

Step three : Sort the hundred
048 075 190 375 629 630 632 794 913 958

OK, the above analysis of the cardinality of the process of sequencing, we know that is a bit-wise to sort on it, but how specifically to arrange the fastest?冒泡排序插入排序快速排序。。。 In fact, these sorts for the general input array speed is relatively fast, but do not forget that there is a qualification, that is, we need to sort the number is the interval is in [0,9] , it is natural that the count is sorted, or the optimal bucket is sorted (with 10 barrels). In the following two methods, we implement these two kinds of sorting separately

Implementation of radix sorting algorithm

The following is a code implementation based on count ordering and optimal bucket ordering. You can download the full source code here:
"Cardinal sort _radixsort": http://download.csdn.net/detail/ii1245712564/8717167

base sort based on count sort

Code for counting sort

/** * Radix sort * @param array input to sort the arrays * @param minele min elements * @param maxele maximum elements * @param arraySize array Size * @ Param radix based on digit 10 bit or hundred etc sort * *voidCountingsort (int Array[] ,intMinele,intMaxele,intArraySize,intRadix) {if(Array= = NULL | |       Minele > Maxele | | ArraySize <0|| Radix <0)return;//Create a new temporary count array    Const int& countarraysize = Maxele-minele+1;intCountarray[countarraysize];//Initialize an array of counts     for(inti =0; i < countarraysize; ++i) {Countarray[i] =0; }//Create a new temporary output array to store the output sort results    intSortedarray[arraysize];//Iterate over array of arrays to count the number of radix for each element     for(inti =0; i < arraySize; ++i) {countarray[Array[I]%radix/(radix/Ten)]++; }//statistic number of elements smaller than one element     for(inti =1; i < countarraysize; ++i) {Countarray[i] = Countarray[i] + countarray[i-1]; }//Put elements in the right place within the Sortedarray     for(inti = arraysize-1; I >=0; I.) {sortedarray[countarray[Array[I]%radix/(radix/Ten)] -1] =Array[i]; countarray[Array[I]%radix/(radix/Ten)]--; }//Copy the elements back, feel a bit slow here, can you do the original sort?      for(inti = arraysize-1; I >=0; -I.) {Array[i] = sortedarray[i]; }return;}

Here the function interface passed in a radix parameter, this radix parameter can only be a multiple of 10 number, array[i]%radix/(radix/10) it is to take out the corresponding bit of the number

Cardinality sort Code

/** * Radix sort * @param array input arrays * @param arraySize array size * @param the maximum number of elements inside the Maxradix array * @param the smallest element inside the Minradix array Bit * /voidRadixsort (int Array[] ,intArraySize,intMinradix,intMaxradix) {if(Array= = NULL | | ArraySize <0|| Maxradix <=0|| Minradix <=0|| Minradix > Maxradix)return;//Get cardinality start position    intTempradix =1; for(inti =1; i < Minradix; ++i) {Tempradix *=Ten; }//Start sorting     for(inti = Minradix; i < Maxradix; ++i) {Tempradix *=Ten; Countingsort (Array,0,9, ArraySize, Tempradix);cout<<tempRadix<<" -----------"<<endl; PrintArray (Array, arraySize); }return;}

Sort the call count sort for each bit in the cardinality sort

Main function code

intMainintargcChar Const*argv[]) {Const int& arraySize =Ten;intInarray[arraysize]; Srand ((int) (Time (NULL))); for(inti =0; i < arraySize; ++i) {Inarray[i] = rand ()% +; }cout<<"before sort array:"<<endl;    PrintArray (InArray, arraySize); Radixsort (InArray, ArraySize,1,4);cout<<"after sort array"<<endl; PrintArray (InArray, arraySize); while(1);return 0;}

Operation Result:
Before sort array:
856 365 404 162 279 512 547 665 70 298
Ten ——— –
70 162 512 404 365 665 856 547 298 279
——— –
404 512 547 856 162 365 665 70 279 298
After sort array
404 512 547 856 162 365 665 70 279 298

base sorting based on optimal bucket ordering

Bucket Sort Code

//define the mapping function for bucket ordering#define BUCKET (i) (i)//define 10 barrelsConst int& bucketnumber =Ten;/** Some code * */** * Bucket sort * @param inArray array of arrays * @param arraySize array size * @param radix corresponding cardinality, can only be multiples of 10 */voidBucketsort (intInarray[],intArraySize,intRadix) {if(InArray = = NULL | | ArraySize <0|| radix<0|| radix%Ten!=0)return;/** Create bucket * /    STD:: vector<int>Buckets[bucketnumber];/** The number of entries in the input array into the bucket * /     for(inti =0; i < arraySize; ++i) {Buckets[bucket (inarray[i]%radix/(radix/Ten))].push_back (Inarray[i]); }/** The array in the bucket in order * /    intArraypos =0; for(inti =0; I < Bucketnumber && Arraypos < arraySize; ++i) {STD:: vector<int>& tempvec = Buckets[i]; for(STD:: vector<int>:: Iterator iter = Tempvec.begin (); Iter! = Tempvec.end ();        ++iter) {inarray[arraypos++] = *iter; }    }}

Here the bucket sort mapping function BUCKET(i) is mapped to i itself, that is, there are n numbers, then create n buckets, which is the fastest bucket sort, but also the most wasteful bucket sorting. radixonly a multiple of 10 is entered here.

Cardinality sort Code

/** * Radix sort * @param inArray input array * @param arraySize array size */voidRadixsort (intInarray[],intArraySize,intMaxplace) {if(InArray = = NULL | | arraysize<0|| Maxplace <1)return;intRadixbasic=1; for(inti =0; i < Maxplace; ++i) {radixbasic*=Ten; Bucketsort (InArray, ArraySize, Radixbasic);cout<<radixBasic<<" -----------"<<endl;    PrintArray (inarray,arraysize); }return;}

Main function code

intMainintargcChar Const*argv[]) {Const int& arraySize =Ten;intInarray[arraysize]; Srand ((int) (Time (NULL))); for(inti =0; i < arraySize; ++i) {Inarray[i] = rand ()% +; }cout<<"before sort array:"<<endl;    PrintArray (InArray, arraySize); Radixsort (InArray, ArraySize,3);cout<<"after sort array"<<endl; PrintArray (InArray, arraySize);return 0;}

Output Result:
Before sort array:
74 864 595 545 957 804 194 942 454 892
Ten ——— –
942 892 74 864 804 194 454 595 545 957
——— –
804 942 545 454 957 864 74 892 194 595
——— –
74 194 454 545 595 804 864 892 942 957
After sort array
74 194 454 545 595 804 864 892 942 957

Base sort _radixsort

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.