-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountSort.java
More file actions
83 lines (71 loc) · 2.18 KB
/
CountSort.java
File metadata and controls
83 lines (71 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package Sorting;
/**
* 1) Non-Comparison
* 2) This sorting Technique is used when Whe Range of input is limited.
* Time Complexity: Worst & Average -O(N + K), Best - O(N), Auxiliary Space: O(N + K)
* k is the time required to find the maximum number.
* It is "Stable Sort" as it does not change the order of the duplicate items.
* It is also "In Place".
*/
public class CountSort {
// Utility Function to Display Array
static void display(int[] a) {
for (int val : a) {
System.out.print(val + " ");
}
System.out.println();
}
// Finding the Max Element.
static int findMax(int[] arr) {
int mx = Integer.MIN_VALUE;
for (int num : arr) {
if (num > mx) mx = num;
}
return mx;
}
// Basic Count Sort Function
static void basicCountSort(int[] arr) {
int max = findMax(arr);
// Frequency Array.
int[] count = new int[max + 1];
for (int value : arr) {
count[value]++;
}
// Adding Elements to Array.
int k = 0;
for (int i = 0; i < count.length; i++) {
for (int j = 0; j < count[i]; j++) {
arr[k++] = i;
}
}
}
// Advanced Count Sort.
static void countSort(int[] arr) {
int n = arr.length;
int[] output = new int[n];
int max = findMax(arr);
// Frequency Array
int[] count = new int[max + 1];
for (int num : arr) {
count[num]++;
}
// Make Prefix sum array of Frequency array
for (int i = 1; i < count.length; i++) {
count[i] += count[i - 1];
}
// Find the index of each element in the original array and put it in output, To Make Stable.
for (int i = n - 1; i >= 0; i--) {
int idx = count[arr[i]] - 1;
output[idx] = arr[i];
count[arr[i]]--;
}
// Copy all elements of output to array.
System.arraycopy(output, 0, arr, 0, n);
}
public static void main(String[] args) {
int[] arr = {1, 4, 5, 2, 2, 5};
countSort(arr);
basicCountSort(arr);
display(arr);
}
}