Download code

Jump to: navigation, search

Back to Counting_sort_(Java)

Download for Windows: single file, zip

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

CountingSort.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/Counting_sort_(Java)?oldid=11981
14 */
15 
16 import java.util.Arrays;
17 import java.util.Random;
18 
19 public class CountingSort {
20     /** Sorts array a where each element is between 0 and numValues-1. */
21     public static void sort(int[] a) {
22         if (a.length == 0)
23 	  return;
24 
25 	int max = a[0], min = a[0];
26 	for (int i = 1; i < a.length; i++) {
27 	    if (a[i] > max)
28 	        max = a[i];
29 	    else if (a[i] < min)
30 	        min = a[i];
31 	}
32 	int numValues = max - min + 1;
33         int[] counts = new int[numValues];
34         for (int i = 0; i < a.length; i++) {
35 	    counts[a[i]-min]++;
36 	}
37 	int outputPos = 0;
38 	for (int i = 0; i < numValues; i++) {
39 	    for (int j = 0; j < counts[i]; j++) {
40 	        a[outputPos] = i+min;
41 	        outputPos++;
42 	    }
43 	}
44     }
45 
46 
47     public static void main(String[] args) {
48         int listSize = Integer.parseInt(args[0]);
49         int numValues = Integer.parseInt(args[1]);
50 
51         // Generate list of random values
52         int[] a = new int[listSize];
53         Random r = new Random();
54         for (int i = 0; i < a.length; i++) {
55             a[i] = r.nextInt(numValues);
56         }
57 
58         // Copy list to new array
59         int[] a2 = new int[listSize];
60         System.arraycopy(a, 0, a2, 0, listSize);
61 
62         // Sort the two arrays
63         sort(a);
64         Arrays.sort(a2);
65 
66         // Compare the two arrays
67         for (int i = 0; i < listSize; i++) {
68             if (a[i] != a2[i]) {
69                 System.out.println("Error: Results do not match.");
70                 return;
71             }
72         }
73         System.out.println("Sort successful");
74     }
75 }


hijacker
hijacker
hijacker
hijacker