Skip to content

Commit f23416a

Browse files
Merge pull request #1 from youssefAli11997/youssefAli11997
Create CountingSortIntegers.java
2 parents f19ca12 + 295ff41 commit f23416a

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

Sorts/CountingSortIntegers.java

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/**
2+
*
3+
* @author Youssef Ali (https://github.com/youssefAli11997)
4+
*
5+
*/
6+
7+
class CountingSortIntegers {
8+
9+
/**
10+
* This method implements the Counting Sort for integers
11+
*
12+
* @param array The array to be sorted
13+
* @param last The count of total number of elements in array
14+
* Sorts the array in increasing order
15+
* It sorted only integer arrays especially positive integers
16+
* It uses array elements as indexes in the frequency array
17+
* Can accept only array elements within the range [0:10^8]
18+
**/
19+
20+
public static void CSI(int array[], int last) {
21+
22+
// The frequency array. It's initialized with zeros
23+
int[] frequency = new int[100000001];
24+
// The final output array
25+
int[] sortedArray = new int[array.length];
26+
int index = 0;
27+
28+
// Counting the frequency of @param array elements
29+
for(int i=0; i<last; i++){
30+
frequency[array[i]]++;
31+
}
32+
33+
// Filling the sortedArray
34+
for(int i=0; i<frequency.length; i++){
35+
for(int j=0; j<frequency[i]; j++)
36+
sortedArray[index++] = i;
37+
}
38+
39+
for(int i=0; i<array.length; i++){
40+
array[i] = sortedArray[i];
41+
}
42+
}
43+
44+
// Driver Program
45+
public static void main(String[] args) {
46+
// Integer Input
47+
int[] arr1 = {4,23,6,78,1,54,231,9,12};
48+
int last = arr1.length;
49+
50+
System.out.println("Before Sorting:");
51+
for (int i=0;i<arr1.length;i++) {
52+
System.out.print(arr1[i] + " ");
53+
}
54+
System.out.println();
55+
56+
CSI(arr1, last);
57+
58+
// Output => 1 4 6 9 12 23 54 78 231
59+
System.out.println("After Sorting:");
60+
for (int i=0;i<arr1.length;i++) {
61+
System.out.print(arr1[i] + " ");
62+
}
63+
System.out.println();
64+
65+
}
66+
}

0 commit comments

Comments
 (0)