Skip to content

Commit 4844be1

Browse files
authored
Update CountingSort.java
1 parent 145dce3 commit 4844be1

File tree

1 file changed

+42
-45
lines changed

1 file changed

+42
-45
lines changed

src/java/CountingSort.java

+42-45
Original file line numberDiff line numberDiff line change
@@ -1,57 +1,54 @@
11
public class CountingSort {
22

3-
int getMax(int[] a, int n) {
4-
int max = a[0];
5-
for (int i = 1; i < n; i++) {
6-
if (a[i] > max)
7-
max = a[i];
8-
}
9-
return max;
3+
int getMax(int[] a, int n) {
4+
int max = a[0];
5+
for (int i = 1; i < n; i++) {
6+
if (a[i] > max) max = a[i];
107
}
8+
return max;
9+
}
1110

12-
void countSort(int[] a, int n) {
13-
int[] output = new int[n + 1];
14-
int max = getMax(a, n);
15-
// int max = 42;
16-
int[] count = new int[max + 1];
11+
void countSort(int[] a, int n) {
12+
int[] output = new int[n + 1];
13+
int max = getMax(a, n);
14+
// int max = 42;
15+
int[] count = new int[max + 1];
1716

18-
for (int i = 0; i <= max; ++i) {
19-
count[i] = 0;
20-
}
21-
22-
for (int i = 0; i < n; i++) {
23-
count[a[i]]++;
24-
}
25-
26-
for (int i = 1; i <= max; i++)
27-
count[i] += count[i - 1];
28-
29-
for (int i = n - 1; i >= 0; i--) {
30-
output[count[a[i]] - 1] = a[i];
31-
count[a[i]]--;
32-
}
17+
for (int i = 0; i <= max; ++i) {
18+
count[i] = 0;
19+
}
3320

34-
for (int i = 0; i < n; i++) {
35-
a[i] = output[i];
36-
}
21+
for (int i = 0; i < n; i++) {
22+
count[a[i]]++;
3723
}
3824

39-
/* Function to print the array elements */
40-
void printArray(int a[], int n) {
41-
int i;
42-
for (i = 0; i < n; i++)
43-
System.out.print(a[i] + " ");
25+
for (int i = 1; i <= max; i++) count[i] += count[i - 1];
26+
27+
for (int i = n - 1; i >= 0; i--) {
28+
output[count[a[i]] - 1] = a[i];
29+
count[a[i]]--;
4430
}
4531

46-
public static void main(String args[]) {
47-
int a[] = { 11, 30, 24, 7, 31, 16, 39, 41 };
48-
int n = a.length;
49-
CountingSort c1 = new CountingSort();
50-
System.out.println("\nBefore sorting array elements are - ");
51-
c1.printArray(a, n);
52-
c1.countSort(a, n);
53-
System.out.println("\nAfter sorting array elements are - ");
54-
c1.printArray(a, n);
55-
System.out.println();
32+
for (int i = 0; i < n; i++) {
33+
a[i] = output[i];
5634
}
35+
}
36+
37+
/* Function to print the array elements */
38+
void printArray(int a[], int n) {
39+
int i;
40+
for (i = 0; i < n; i++) System.out.print(a[i] + " ");
41+
}
42+
43+
public static void main(String args[]) {
44+
int a[] = {11, 30, 24, 7, 31, 16, 39, 41};
45+
int n = a.length;
46+
CountingSort c1 = new CountingSort();
47+
System.out.println("\nBefore sorting array elements are - ");
48+
c1.printArray(a, n);
49+
c1.countSort(a, n);
50+
System.out.println("\nAfter sorting array elements are - ");
51+
c1.printArray(a, n);
52+
System.out.println();
53+
}
5754
}

0 commit comments

Comments
 (0)