forked from utkarsh-shekhar/basic-programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountingSort.java
More file actions
40 lines (36 loc) · 1.2 KB
/
CountingSort.java
File metadata and controls
40 lines (36 loc) · 1.2 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
import java.util.Arrays;
import java.util.Random;
public class CountingSort {
//Implementation of Counting Sort
public static int[] sort(int[] inputArray) {
int[] countArray = new int[100000];
int[] sortedArray = new int[inputArray.length];
Arrays.fill(countArray, 0);
for (int i = 0; i < inputArray.length; i++) {
countArray[inputArray[i] - 1]++;
}
for (int i = 1; i < countArray.length; i++) {
countArray[i] += countArray[i - 1];
}
for (int i = inputArray.length - 1; i >= 0; i--) {
sortedArray[countArray[inputArray[i] - 1] - 1] = inputArray[i];
countArray[inputArray[i] - 1]--;
}
return sortedArray;
}
//Calling sort() function to test Counting Sort
public static void main(String[] args) {
Random rd = new Random();
int[] inputArray = new int[100];
System.out.println("Input Array:");
for (int i = 0; i < inputArray.length; i++) {
inputArray[i] = rd.nextInt(100000) + 1;
System.out.print(inputArray[i] + " ");
}
System.out.println("\nSorted Array:");
int[] sortedArray = sort(inputArray);
for (int i = 0; i < sortedArray.length; i++) {
System.out.print(sortedArray[i] + " ");
}
}
}