Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package countingsort;
- public class CountSort {
- private int[] intAArr;
- public CountSort(int[] arr) {
- this.setArr(arr);
- }
- public int[] getArr() {
- return this.copyArr(intAArr);
- }
- public void setArr(int[] arr) {
- if (arr != null) {
- this.intAArr = this.copyArr(arr);
- } else {
- this.intAArr = new int[5];
- }
- }
- public int[] sort() {
- int[] intBArr = new int[this.intAArr.length]; // Sorted Elements
- int k = this.getMax();
- int[] countArray = new int[k + 1]; // Count Array
- // Count each element in the given array and
- // place the count at the appropriate index
- for (int i = 0; i < intAArr.length; i++) {
- countArray[intAArr[i]]++;
- }
- // Modify the count array by adding the previous counts.
- for (int i = 1; i <= k; i++) {
- countArray[i] += countArray[i - 1];
- }
- // DESCENDING
- // for (int i = k - 1; i >= 0; i--) {
- // intCArr[i] += intCArr[i + 1];
- // }
- // Corresponding values represent the places in the count array
- // We place the objects in their correct positions and decrease the count by one
- for (int i = intAArr.length - 1; i >= 0; i--) {
- int index = countArray[intAArr[i]] - 1;
- intBArr[index] = intAArr[i];
- countArray[intAArr[i]]--;
- }
- return intBArr;
- }
- private int getMax() {
- int maxEl = Integer.MIN_VALUE;
- for (int i = 0; i < this.intAArr.length; i++) {
- if (this.intAArr[i] > maxEl) {
- maxEl = this.intAArr[i];
- }
- }
- return maxEl;
- }
- private int[] copyArr(int[] arr) {
- int[] copyArr = new int[arr.length];
- for (int i = 0; i < arr.length; i++) {
- if (arr[i] >= 0) {
- copyArr[i] = arr[i];
- } else {
- copyArr[i] = 0;
- }
- }
- return copyArr;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement