-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountSort.java
More file actions
44 lines (39 loc) · 1.22 KB
/
CountSort.java
File metadata and controls
44 lines (39 loc) · 1.22 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
class CountSort {
public static void countSort(int arr[]){
//finding largest element of the array
int largest = Integer.MIN_VALUE;
for(int i = 0; i < arr.length; i++){
if(arr[i] > largest){
largest = arr[i];
}
}
//creating count array of size {largest element + 1} for frequency maintaining
int count[] = new int[largest+1];
//maintaining frequency in count arrays of elements of original array
for(int i = 0; i < arr.length; i++){
count[arr[i]]++;
}
//sorting the original array
int j = 0;
for(int i = 0; i < count.length; i++){
while(count[i] > 0){
arr[j] = i;
j++;
count[i]--;
}
}
}
public static void main(String[] args) {
int[] arr = {4,1,3,1,4,2,7,3};
System.out.println("Array before Count sort : ");
for(int val : arr){
System.out.print(val + " ");
}
System.out.println();
countSort(arr);
System.out.println("Array after Count sort : ");
for(int val : arr){
System.out.print(val + " ");
}
}
}