• API
• FAQ
• Tools
• Archive
daily pastebin goal
57%
SHARE
TWEET

# FullClass

a guest Nov 14th, 2017 56 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. package countingsort;
2.
3. public class CountSort {
4.
5.     private int[] intAArr;
6.
7.     public CountSort(int[] arr) {
8.         this.setArr(arr);
9.     }
10.
11.     public int[] getArr() {
12.         return this.copyArr(intAArr);
13.     }
14.
15.     public void setArr(int[] arr) {
16.         if (arr != null) {
17.             this.intAArr = this.copyArr(arr);
18.         } else {
19.             this.intAArr = new int[5];
20.         }
21.     }
22.
23.     public int[] sort() {
24.         int[] intBArr = new int[this.intAArr.length]; // Sorted Elements
25.         int k = this.getMax();
26.         int[] countArray = new int[k + 1]; // Count Array
27.
28.         // Count each element in the given array and
29.         // place the count at the appropriate index
30.         for (int i = 0; i < intAArr.length; i++) {
31.             countArray[intAArr[i]]++;
32.         }
33.
34.         // Modify the count array by adding the previous counts.
35.         for (int i = 1; i <= k; i++) {
36.             countArray[i] += countArray[i - 1];
37.         }
38.
39.          // DESCENDING
40. //        for (int i = k - 1; i >= 0; i--) {
41. //            intCArr[i] += intCArr[i + 1];
42. //        }
43.
44.         // Corresponding values represent the places in the count array
45.         // We place the objects in their correct positions and decrease the count by one
46.         for (int i = intAArr.length - 1; i >= 0; i--) {
47.             int index = countArray[intAArr[i]] - 1;
48.             intBArr[index] = intAArr[i];
49.             countArray[intAArr[i]]--;
50.         }
51.
52.         return intBArr;
53.     }
54.
55.     private int getMax() {
56.         int maxEl = Integer.MIN_VALUE;
57.
58.         for (int i = 0; i < this.intAArr.length; i++) {
59.             if (this.intAArr[i] > maxEl) {
60.                 maxEl = this.intAArr[i];
61.             }
62.         }
63.
64.         return maxEl;
65.     }
66.
67.     private int[] copyArr(int[] arr) {
68.         int[] copyArr = new int[arr.length];
69.         for (int i = 0; i < arr.length; i++) {
70.             if (arr[i] >= 0) {
71.                 copyArr[i] = arr[i];
72.             } else {
73.                 copyArr[i] = 0;
74.             }
75.         }
76.
77.         return copyArr;
78.     }
79. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.

Top