Download code

Jump to: navigation, search

Back to Radix_sort_(Java)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

RadixSort.java

 1 /* The authors of this work have released all rights to it and placed it
 2 in the public domain under the Creative Commons CC0 1.0 waiver
 3 (http://creativecommons.org/publicdomain/zero/1.0/).
 4 
 5 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 
13 Retrieved from: http://en.literateprograms.org/Radix_sort_(Java)?oldid=12461
14 */
15 
16 import java.util.Arrays;
17 
18 
19 class RadixSort
20 {
21     public static void radix_sort_uint(int[] a, int bits)
22     {
23         int[] b = new int[a.length];
24         int[] b_orig = b;
25 
26         int rshift = 0;
27         for (int mask = ~(-1 << bits); mask != 0; mask <<= bits, rshift += bits) {
28             int[] cntarray = new int[1 << bits];
29             for (int p = 0; p < a.length; ++p) {
30                 int key = (a[p] & mask) >> rshift;
31                 ++cntarray[key];
32             }
33 
34     		for (int i = 1; i < cntarray.length; ++i)
35                         cntarray[i] += cntarray[i-1];
36 
37             for (int p = a.length-1; p >= 0; --p) {
38                 int key = (a[p] & mask) >> rshift;
39                 --cntarray[key];
40                 b[cntarray[key]] = a[p];
41             }
42 
43             int[] temp = b; b = a; a = temp;
44         }
45 
46         if (a == b_orig)
47             System.arraycopy(a, 0, b, 0, a.length);
48     }
49     public static void main(String[] args)
50     {
51         int[] a = {
52             123,432,654,3123,654,2123,543,131,653,123,
53             533,1141,532,213,2241,824,1124,42,134,411,
54             491,341,1234,527,388,245,1992,654,243,987};
55 
56         System.out.println("Before radix sort:");
57         System.out.println(Arrays.toString(a));
58 
59         radix_sort_uint(a, 4);
60 
61         System.out.println("After radix sort:");
62         System.out.println(Arrays.toString(a));
63     }
64 }
65 


hijacker
hijacker
hijacker
hijacker