-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCounting Sort in Java
More file actions
58 lines (47 loc) · 1.53 KB
/
Counting Sort in Java
File metadata and controls
58 lines (47 loc) · 1.53 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
public class CountingSort {
// Method to perform counting sort
public static void countingSort(int[] arr) {
int n = arr.length;
// Find the maximum element in the array
int max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
// Create a count array to store the count of each unique element
int[] count = new int[max + 1];
// Store the count of each element in the count array
for (int i = 0; i < n; i++) {
count[arr[i]]++;
}
// Modify the count array by adding the previous counts
for (int i = 1; i <= max; i++) {
count[i] += count[i - 1];
}
// Output array to store the sorted elements
int[] output = new int[n];
// Build the output array
for (int i = n - 1; i >= 0; i--) {
output[count[arr[i]] - 1] = arr[i];
count[arr[i]]--;
}
// Copy the sorted elements into the original array
for (int i = 0; i < n; i++) {
arr[i] = output[i];
}
}
public static void main(String[] args) {
int[] arr = {4, 2, 2, 8, 3, 3, 1};
System.out.println("Unsorted array:");
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
countingSort(arr);
System.out.println("Sorted array:");
for (int num : arr) {
System.out.print(num + " ");
}
}
}