Skip to content

Commit 005380f

Browse files
ani03shaAnirudh Sharma
authored and
Anirudh Sharma
committed
Added Pigeonhole Sort with its corresponding test cases
1 parent c22449a commit 005380f

File tree

2 files changed

+86
-0
lines changed

2 files changed

+86
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package src.main.java.com.sorts;
2+
3+
public class PigeonholeSort {
4+
5+
/**
6+
* This method sorts the array using Pigeonhole sort technique.
7+
* <p>
8+
* Pigeonhole sorting is a sorting algorithms that is suitable for sorting lists of elements where the number
9+
* of elements and the number of possible key values are approximately the same.
10+
* <p>
11+
* It requires O(n + Range) time where n is number of elements in input array and ‘Range’ is number of possible
12+
* values in array.
13+
*
14+
* @param arr The array to be sorted
15+
* @return arr Sorted array
16+
*/
17+
public Integer[] sort(Integer[] arr) {
18+
19+
// Find maximum and minimum elements in array
20+
int min = arr[0];
21+
int max = arr[0];
22+
23+
for (Integer integer : arr) {
24+
25+
// For minimum value
26+
if (min > integer) {
27+
min = integer;
28+
}
29+
30+
// For maximum value
31+
if (max < integer) {
32+
max = integer;
33+
}
34+
}
35+
36+
// Range
37+
int range = max - min + 1;
38+
39+
// Pigeonhole array
40+
int[] pigeonholes = new int[range];
41+
42+
// Put each element of arr in its pigeonhole
43+
for (Integer integer : arr) {
44+
pigeonholes[integer - min] = integer;
45+
}
46+
47+
// Index for the arr
48+
int index = 0;
49+
50+
// 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;
56+
}
57+
}
58+
59+
return arr;
60+
}
61+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
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.PigeonholeSort;
6+
7+
public class PigeonholeSortTest {
8+
9+
@Test
10+
public void testPigeonholeSort() {
11+
12+
PigeonholeSort pigeonholeSort = new PigeonholeSort();
13+
14+
// Test Case 1
15+
Integer[] unsorted1 = new Integer[]{5, 1, 7, 2, 9, 6, 3, 4, 8};
16+
Integer[] sorted1 = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9};
17+
Assert.assertArrayEquals(sorted1, pigeonholeSort.sort(unsorted1));
18+
19+
// Test Case 2
20+
Integer[] unsorted2 = new Integer[]{-5, 1, 7, 2, -9, 6, -3, 4, 8};
21+
Integer[] sorted2 = new Integer[]{-9, -5, -3, 1, 2, 4, 6, 7, 8};
22+
Assert.assertArrayEquals(sorted2, pigeonholeSort.sort(unsorted2));
23+
24+
}
25+
}

0 commit comments

Comments
 (0)