Counting sort

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
import java.util.*;

public class Counting_sort {
static int[] countingSort(int[] a) {
int maxValue=0;
for (int i : a) maxValue=i>maxValue?i:maxValue;

int c[] = new int[maxValue + 1];
for (int i = 0; i < a.length; i++) c[a[i]]++;

int b[] = new int[a.length];

int count = 0;
for (int i = 0; i <= maxValue; i++) {
while (c[i] > 0) {
b[count++] = i;
c[i]--;
}
}
return b;
}

// *********************************************
public static void main(String[] args) {
int[] arr = { 2, 5, 8, 0, 4, 2, 1 };
System.out.println(Arrays.toString(countingSort(arr)));
}
}
0%