I. Question
How to sort the N integers between 0 and N ^ 2-1 in O (n) Time
Ii. Train of Thought to convert the integer into N in hexadecimal order and then sort the number. Each number has two digits. The value range of each digit is [0 .. n-1], and then sort the base number.
Iii. Code
[CPP]
View plaincopyprint?
- # Include <iostream>
- # Include <cmath>
- Using namespace STD;
- Int N, Radix, length_a, digit = 2;
- Void print (int * a, int start, int end)
- {
- Int I;
- For (I = start; I <= end; I ++)
- {
- If (I = Start) cout <'{';
- Else cout <'';
- Cout <A [I];
- }
- Cout <'}' <Endl;
- }
- // Stable sorting of base sort calls
- Void stable_sort (int * a, int * B, int K, int D)
- {
- Int I, J;
- // Initialize the C array to 0 for counting
- Int * c = new int [k + 1];
- For (I = 0; I <= K; I ++)
- C [I] = 0;
- Int * D = new int [length_a + 1];
- For (j = 1; j <= length_a; j ++)
- {
- // D [J] indicates the I-digit number of the [J] Element
- D [J] = A [J] % (INT) Pow (Radix * 1.0, d)/(INT) Pow (Radix * 1.0, D-1 );
- // C [J] indicates the number of times the number d [J] appears in array.
- C [d [J] ++;
- }
- // C [I] indicates the number of times that the <= I number has appeared.
- For (I = 1; I <= K; I ++)
- C [I] = C [I] + C [I-1];
- // Initialize B to 0 and B to output the sorting result
- For (I = 1; I <= length_a; I ++)
- B [I] = 0;
- For (j = length_a; j> = 1; j --)
- {
- // If the number of numbers <= d [J] is X, after sorting, a [J] should appear at position X, that is, B [x] = A [J]
- B [C [d [J] = A [J];
- C [d [J] --;
- }
- Delete [] C;
- Delete [] D;
- }
- // Base sorting
- Void radix_sort (int * a, int * B)
- {
- Int I, J;
- // Sort each bit in sequence, from low to high
- For (I = 1; I <= digit; I ++)
- {
- Stable_sort (a, B, Radix-1, I );
- // The input is A, the output is B, and the output data should be put into the output data when sorting again
- For (j = 1; j <= length_a; j ++)
- A [J] = B [J];
- }
- }
- Int main ()
- {
- Cin> N;
- Length_a = N;
- Int * A = new int [n + 1];
- Int * B = new int [n + 1];
- Bool flag [1000] = {0 };
- Int I;
- // Generate n random data ranges from 0 to N ^-1.
- For (I = 1; I <= N; I ++)
- {
- Do
- {
- A [I] = rand () % (n * n );
- } While (flag [A [I]);
- Flag [A [I] = 1;
- }
- Print (A, 1, n );
- Radix = N;
- Radix_sort (A, B );
- Print (A, 1, n );
- Return 0;
- }
Reprinted from: http://blog.csdn.net/mishifangxiangdefeng/article/details/7685839