Base number sorting of mobile phone numbers

     Originally published in:

 

     The seven common sorts are: bubble sort, selection sort, insertion sort, merge sort, hill sort, quick sort and heap sort. They are all sorts based on comparison, and the time complexity is best to reach O(NlogN).  

     The three special sorts are: counting sorting, bucket sorting, and cardinal sorting. They are non-comparative sorts, and their time complexity is linear.

     In some written interview questions, the sorting algorithm is almost inevitably involved, especially for school recruitment.

 

 

      First look at such a problem:

      There are n mobile phone numbers, try to sort, and require the time complexity to be as low as possible.

      Seven common sorts, the time complexity certainly does not meet the requirements. Count sorting is suitable for positive integers with a small data range, and bucket sorting is suitable for data with a small data range and relatively uniform distribution. If you want to sort the phone numbers, use the base sort.

 

 

     In order to simplify the description, we sort 321, 145, 241, 116, 742, 532, and the radix sorting process is as follows:

       a. Count and sort the ones place

       b. Count and sort the tens place

       c. Count and sort hundreds

 

     The above three counting and sorting steps are combined to form a base sort. At this time, the "base" of cardinality sorting actually refers to the base composed of 10 numbers 0-9. The radix sorting diagram is as follows:

      

     From the process of radix sorting, it can be seen that the time complexity is O(d*n), where n is the number of numbers to be sorted, and d is the number of digits in each element. In the above figure, d=3 , n=6. It is easy to know that the radix sort is the sort of linear time complexity.

     Let's look at the sorting problem of telephone numbers again. The 11-digit telephone number is sorted by the base number, and the time complexity is O(11*n), which is also a linear time complexity sort.

 

     We noticed that in the above example, the number of bits of each data is the same, in fact, this is not a hard requirement for cardinal sorting. When the digits of the data are not equal, you can completely fill in the zeros in front to make up data with equal digits.

 

     The idea of ​​radix sorting algorithm is very clever, the code implementation is very simple, so I won’t go into details. Thinking is more important.

 

Guess you like

Origin blog.csdn.net/stpeace/article/details/108418001