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
# 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_sort (int * a, int * B, int K, int d) {int I, j; // initialize the C array to 0, used to count 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 element [J] 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 a 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, B is used 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 sort 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 placed in the output data 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 ;}