public class CountingSort {
public static void main(String[] args) {
// Array of items on which search will
// be conducted.
int arr[] = new int[] { 10, 12, 13, 16, 18, 19, 20, 21, 22, 23, 24, 33, 35, 42, 47 };
int maxElemnt = findMaxElement(arr);
arr = countSort(arr, maxElemnt);
System.out.println("Below is the sorted array:");
for (int s : arr)
System.out.print(s + " ");
}
// Finding Max Element
public static int findMaxElement(int[] arr) {
int i = 0;
int temp;
while (i < arr.length - 1) {
if (arr[i] > arr[i + 1]) {
temp = arr[i + 1];
arr[i + 1] = arr[i];
arr[i] = temp;
}
i++;
}
return arr[arr.length - 1];
}
public static int[] countSort(int[] arr, int range) {
int[] countArray = new int[range + 1];
int[] outputArray = new int[arr.length];
int i = 0;
while (i < arr.length) {
countArray[arr[i]] = ++countArray[arr[i]];
i++;
}
i = 1;
while (i < countArray.length) {
countArray[i] = countArray[i] + countArray[i - 1];
i++;
}
i = 0;
while (i < outputArray.length) {
outputArray[countArray[arr[i]] - 1] = arr[i];
countArray[arr[i]] = --countArray[arr[i]];
i++;
}
return outputArray;
}
}
No comments:
Post a Comment