Algorithm learning-base sorting of linear time sorting, counting sorting and java Implementation

Source: Internet
Author: User

First introduce the concept
Both count sorting and base sorting are non-Comparative sorting, that is, they can be sorted without comparison. Compared with heap sorting, quick sorting, and insertion sorting, they are all comparative sorting, in the worst case of a comparative sorting algorithm, a comparison of 0 (nlgn) times will be performed next time. The heap sorting and Merge Sorting are both the closest and closer comparison sorting algorithms, the time complexity of linear time sorting is O (n ).
The basic idea of counting sorting. Assume that each of the n input elements is an integer ranging from 0 to k. Here k is an integer. When k = O (n), the running time of counting sorting is O (n). The basic idea of counting sorting is to determine the number of elements smaller than x for each input element x, in this way, x can be directly placed at the final output position. For example, if 15 elements are smaller than x, x is placed at 18th output locations. When elements are the same, the number of elements smaller than the number must be reduced by 1.
In addition, two arrays are required to store the final result array and the temporary storage array (that is, the number less than x ).
It is stable. The relative order of elements with the same value in the output array is the same as that in the input array.

The basic idea of base sorting is that base sorting is an extended barrel sorting. For example, when the columns to be sorted are within a large range, such as 0 to 999999, therefore, bucket sorting is a waste of space. The base sorting splits each sort code into d sort codes. For example, if a 6-digit sorting code is divided into 6 sort codes (with less than six digits, the first 0 is added), the sorting code is a single-digit sorting code, ten-digit, hundred-digit ....
There are two methods:
1) high priority (MSD): sort the sequence from high to low.
2) low priority (LSD): sequence sorting from low to high
Computers generally adopt the low priority method (generally, humans use high priority), but when low priority is adopted, the stability of the sorting algorithm should be ensured.
The base sorting uses the bucket sorting method. Each time the data is sorted by the nth bit, the data is sorted by the bucket. There are two ways to arrange data that falls into the same bucket each time:
1) sequential storage: Sort buckets in r buckets each time, and increase the count at the same time.
2) chained storage: each bucket is tracked through a static queue.
For example:
Now there are Arrays: 78,189,354, 8,756,390,356. For the first time, an array is divided into 10 queues based on the number of queues (of course, some of these queues may not contain any element)
, 390
1:
2: 2
3:
4:354
5:
6: 756,356
7:
8: 78, 8
9: 189
Then the integration sequence is received:
10,390, 2,354,756,356, 189
In the second group:
0: 2, 8
1: 10
2:
3:
4:
, 756,356
6:
7: 78
8: 189
9: 390
Second collection:
10,354,756,356, 78,189,390
Third allocation:
0: 2, 8, 10, 78
1: 189
2:
, 356,390
4:
5:
6:
7: 756
8:
9:
Finally, we obtain the sequence 189,354,356,390,756. Sort finished!
In fact, the base sorting is to use multiple keywords to first reach the local order, and then adjust to the global order.
Although there are common cases where B = O (lgn) and the running time of the base sorting is round (n), it looks better than the average round (nlgn) of the fast sorting. However, the constant factors hidden in the scalar symbol are different. For the n keywords to be processed, although the number of times the base sort is executed is less than the number of times in the fast sorting, the time for each time is longer, so which sort is better, it depends on the implementation features of the underlying machine (for example, fast sorting can usually make better use of the hardware cache than the base), but also on the input data. In addition, counting sorting is used as the base sorting for intermediate stable sorting instead of in-situ sorting, while many sort (nlgn) Comparison sorting algorithms can achieve in-situ sorting. Therefore, when memory capacity is precious, in-situ sorting algorithms such as fast sorting may be more valuable. (From introduction to algorithms)
Bucket sorting: the basic idea is to divide the interval [0, 1] into n subintervals of the same size, also called buckets, and then distribute n inputs to buckets. Because the input is even, there is usually not a large number of buckets. When outputting, sort each bucket first, and then output each bucket element in sequence. Its pseudo code is as follows:

Code writing is more detailed, not to mention. The code and comments are clear.

Specific implementation:
  
[Java]
Package sort;
 
Import java. util .*;
 
Public class RadixSort {
/**
* Principle of the base Sorting Algorithm:
* First, find the maximum number of digits, and then determine the number of sorting times,
* Create 10 arrays to store numbers with the nth digits 0, 1, 2... 9,
* After storing the data, you need to collect the numbers in 10 arrays to the original array,
* Then sort
* The number of digits I is 0, 1, 2... 9. Calculation Method: array [j] % Math. pow (10, I + 1)/Math. pow (10, I)
* That is, the first digit is divided by the remainder of 10. The second digit is divided by the remainder of 100, and the quotient of 10 is the second digit, and so on.
*
* @ Param array
* Array for base sorting
*/
Public void radixSort (int [] array ){
Int max, time;
// Determine the maximum number of digits and the number of sorting times.
Max = array [0];
For (int I = array. length-1; I> 0; I --){
If (max <array [I]) {
Max = array [I];
}
}
Time = 0;
While (max> 0 ){
Max/= 10;
Time ++;
}
// Create 10 Arrays
ArrayList <Integer> [] quene = new ArrayList [10];
For (int I = 0; I <10; I ++ ){
Quene [I] = new ArrayList <Integer> ();
}
 
// Time allocation and collection arrays are respectively carried out, allocated to the array according to different digits, and then collected to the original array
For (int I = 0; I <time; I ++ ){
For (int j = 0; j <array. length; j ++ ){
Int index = (int) (array [j] % (int) Math. pow (10, I + 1)/Math
. Pow (10, I ));
Quene [index]. add (array [j]);
}
// Allocate data after collection
Int count = 0;
For (int k = 0; k <10; k ++ ){
While (quene [k]. size ()> 0 ){
Array [count] = quene [k]. remove (0 );
Count ++;
}
}
}
}
 
/**
* Basic idea of counting sorting:
* Calculate the number of elements smaller than x in each element x in the array,
* Then you can place x in the corresponding position.
* For example, if there are 15 numbers less than x, then x is located at the 16th position.
*
* @ Param data
* Array to be sorted
* @ Param k
* Maximum number of sorted Arrays
*/
Public int [] countingSort (int [] data, int k ){
Int result [] = new int [data. length];
Int [] temp = new int [k + 1];
// Initialize the temporary array first, that is, to save an array smaller than the number of element x
For (int I = 0; I <temp. length; I ++ ){
Temp [I] = 0;
}
// Temp [I] indicates the number of elements equal to I.
For (int I = 0; I <data. length; I ++ ){
Temp [data [I] = temp [data [I] + 1;
}
// Temp [I] indicates the number of elements smaller than or equal to I.
For (int I = 1; I <temp. length; I ++ ){
Temp [I] = temp [I] + temp [I-1];
}
// Put the result in the result array, and A [j] is directly placed in the final position (less than or equal to the number of A [j] plus 1)
// For temp [data [j] + 1, the array subscript and position differ by 1.
For (int j = data. length-1; j> = 0; j --){
Int index = temp [data [j];
Result [index-1] = data [j];
Temp [data [j] --;
}
Return result;
}
 
/**
* Obtain the maximum number in the array for counting and sorting.
*
* @ Param data
* Array to be calculated
* @ Return returns the maximum number.
*/
Public int getMax (int [] data ){
Int max = data [0];
For (int I = data. length-1; I> 0; I --){
If (max <data [I]) {
Max = data [I];
}
}
Return max;
}
 
Public static void main (String [] args ){
RadixSort redix = new RadixSort ();
Int [] testData = {78,189,354, 8,756,390,356 };
// Base Sorting Test
System. out. println ("*** base Sorting Test ***");
Redix. radixSort (testData );
For (int data: testData ){
System. out. print (data + ",");
}
 
// Count Sorting Test
System. out. println ("\ n *** count Sorting Test ***");
Int [] testData2 = {9, 3, 5, 3, 6, 5, 3, 7, 4, 9 };
Int max = redix. getMax (testData2 );
Int [] countSort = redix. countingSort (testData2, max );
For (int data: countSort ){
System. out. print (data + ",");
}
}
 
}

The result is as follows:

  

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.