Skip to content

Commit 9fe55c8

Browse files
ani03shaAnirudh Sharma
authored andcommitted
Added Pigeonhole Sort with its corresponding test cases
1 parent 005380f commit 9fe55c8

2 files changed

Lines changed: 15 additions & 7 deletions

File tree

src/main/java/src/main/java/com/sorts/PigeonholeSort.java

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -41,18 +41,21 @@ public Integer[] sort(Integer[] arr) {
4141

4242
// Put each element of arr in its pigeonhole
4343
for (Integer integer : arr) {
44-
pigeonholes[integer - min] = integer;
44+
// This increment operation will count for the duplicates elements, if present
45+
pigeonholes[integer - min]++;
4546
}
4647

47-
// Index for the arr
48+
// Index for the original array
4849
int index = 0;
4950

5051
// Loop over pigeonhole array
51-
for (int pigeonhole : pigeonholes) {
52-
53-
// Put non zero elements from the pigeonhole array to the current element of arr
54-
if (pigeonhole != 0) {
55-
arr[index++] = pigeonhole;
52+
for (int i = 0; i < range; i++) {
53+
// This inner loop will execute only for those indexes in
54+
// pigeonhole which are greater than zero i.e., only for those
55+
// elements which are present in the original array. This also
56+
// takes care of the duplicate elements
57+
while (pigeonholes[i]-- > 0) {
58+
arr[index++] = i + min;
5659
}
5760
}
5861

src/test/java/src/test/java/com/sorts/PigeonholeSortTest.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,5 +21,10 @@ public void testPigeonholeSort() {
2121
Integer[] sorted2 = new Integer[]{-9, -5, -3, 1, 2, 4, 6, 7, 8};
2222
Assert.assertArrayEquals(sorted2, pigeonholeSort.sort(unsorted2));
2323

24+
// Test Case 3
25+
Integer[] unsorted3 = new Integer[]{-5, 1, 7, 2, -9, 6, -3, 4, 1, 8, 1, 1};
26+
Integer[] sorted3 = new Integer[]{-9, -5, -3, 1, 1, 1, 1, 2, 4, 6, 7, 8};
27+
Assert.assertArrayEquals(sorted3, pigeonholeSort.sort(unsorted3));
28+
2429
}
2530
}

0 commit comments

Comments
 (0)