8000 Count sort code · harshspandey1/DSA-Bootcamp-Java@d573972 · GitHub
[go: up one dir, main page]

Skip to content

Commit d573972

Browse files
Count sort code
1 parent d74475e commit d573972

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import java.util.*;
2+
3+
class Main {
4+
5+
public static void countSort(int[] array) {
6+
if(array == null || array.length <= 1) {
7+
return;
8+
}
9+
10+
int max = array[0];
11+
for(int num : array) {
12+
if(num > max) {
13+
max = num;
14+
}
15+
}
16+
17+
int[] countArray = new int[max + 1];
18+
19+
for(int num : array) {
20+
countArray[num]++;
21+
}
22+
23+
int index = 0;
24+
for(int i=0; i<= max; i++) {
25+
while(countArray[i] > 0) {
26+
array[index] = i;
27+
index++;
28+
countArray[i]--;
29+
}
30+
}
31+
32+
}
33+
34+
public static void countSortHash(int[] arr) {
35+
if(arr == null || arr.length <= 1) {
36+
return;
37+
}
38+
39+
int max = Arrays.stream(arr).max().getAsInt();
40+
int min = Arrays.stream(arr).min().getAsInt< 8000 /span>();
41+
42+
Map<Integer, Integer> countMap = new HashMap<>();
43+
44+
for(int num : arr) {
45+
countMap.put(num, countMap.getOrDefault(num, 0) + 1);
46+
}
47+
48+
int index = 0;
49+
for(int i=min; i<=max; i++) {
50+
int count = countMap.getOrDefault(i, 0);
51+
for(int j=0; j < count; j++) {
52+
arr[index] = i;
53+
index++;
54+
}
55+
}
56+
57+
}
58+
59+
public static void main(String[] args) {
60+
int[] arr = {6, 3, 10, 9, 2, 4, 9, 7};
61+
countSortHash(arr);
62+
System.out.println(Arrays.toString(arr));
63+
}
64+
}

0 commit comments

Comments
 (0)
0