Skip to content

Commit e15d329

Browse files
ani03shaAnirudh Sharma
authored and
Anirudh Sharma
committed
Added algorithm class CountingSort and its corresponding test class CountingSortTest
1 parent f65fc4d commit e15d329

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package src.main.java.com.sorts;
2+
3+
public class CountingSort {
4+
5+
/**
6+
* This method sorts the array using counting sort technique
7+
*
8+
* @param arr The array to be sorted
9+
* @return arr Sorted array
10+
*/
11+
public Integer[] sort(Integer[] arr) {
12+
13+
// Finding the maximum element in the array
14+
int max = arr[0];
15+
for (int i = 1; i < arr.length; i++) {
16+
max = Math.max(max, arr[i]);
17+
}
18+
19+
// Creating the count array - This method will store the count of each element in the unsorted array
20+
int[] count = new int[max + 1];
21+
22+
// This loop will store the count of each element in the array
23+
for (int i = 0; i < max; i++) {
24+
25+
count[arr[i]]++;
26+
}
27+
28+
// This loop will replace the ith index of the count array with the sum of values at the ith and (i-1) index
29+
for (int i = 1; i < count.length; i++) {
30+
31+
count[i] = count[i] + count[i - 1];
32+
}
33+
34+
// This array will store the sorted array
35+
Integer[] places = new Integer[arr.length];
36+
37+
// This loop will put the ith element at is correct position in the places array
38+
for (int i = 0; i < places.length; i++) {
39+
40+
// Getting the value of the index - the value at the oount array index will be replaced by the value
41+
// in the original array
42+
int index = arr[i];
43+
places[count[index] - 1] = index;
44+
count[index]--;
45+
}
46+
47+
// Copy the places array back to the original array - which will be sorted
48+
System.arraycopy(places, 0, arr, 0, arr.length);
49+
50+
return arr;
51+
}
52+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package src.test.java.com.sorts;
2+
3+
import org.junit.Assert;
4+
import org.junit.Test;
5+
import src.main.java.com.sorts.CountingSort;
6+
7+
public class CountingSortTest {
8+
9+
@Test
10+
public void testCountingSort() {
11+
12+
CountingSort countingSort = new CountingSort();
13+
14+
// Unsorted integer array
15+
Integer[] unsorted = new Integer[]{1, 4, 1, 2, 7, 5, 2};
16+
17+
// Sorted integer array
18+
Integer[] sorted = new Integer[]{1, 1, 2, 2, 4, 5, 7};
19+
20+
// Comparing the two integer arrays
21+
Assert.assertArrayEquals(sorted, countingSort.sort(unsorted));
22+
}
23+
}

0 commit comments

Comments
 (0)