
Pigeonhole Sort is an algorithm that sorts data by distributing elements into “pigeonholes” (buckets) based on their values. It is particularly effective when the range of data values is small and the data consists of integers.
import java.util.ArrayList;
public class PigeonholeSort {
public static void pigeonholeSort(int[] arr) {
int min = arr[0];
int max = arr[0];
int n = arr.length;
// Find the minimum and maximum values
for (int i = 1; i < n; i++) {
if (arr[i] < min) {
min = arr[i];
}
if (arr[i] > max) {
max = arr[i];
}
}
int range = max - min + 1; // Range of the values in the array
ArrayList<Integer>[] pigeonholes = new ArrayList[range];
// Initialize pigeonholes
for (int i = 0; i < range; i++) {
pigeonholes[i] = new ArrayList<>();
}
// Place elements into pigeonholes
for (int num : arr) {
pigeonholes[num - min].add(num);
}
// Collect sorted elements
int index = 0;
for (ArrayList<Integer> hole : pigeonholes) {
for (int num : hole) {
arr[index++] = num;
}
}
}
public static void main(String[] args) {
int[] arr = {8, 3, 2, 7, 4, 6, 8, 1, 9};
System.out.println("Original Array:");
for (int num : arr) {
System.out.print(num + " ");
}
pigeonholeSort(arr);
System.out.println("\nSorted Array:");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
def pigeonhole_sort(arr):
# Find minimum and maximum values
min_val = min(arr)
max_val = max(arr)
range_size = max_val - min_val + 1
# Create pigeonholes
pigeonholes = [[] for _ in range(range_size)]
# Place elements into pigeonholes
for num in arr:
pigeonholes[num - min_val].append(num)
# Collect sorted elements
sorted_arr = []
for hole in pigeonholes:
sorted_arr.extend(hole)
return sorted_arr
# Example usage
if __name__ == "__main__":
arr = [8, 3, 2, 7, 4, 6, 8, 1, 9]
print("Original Array:", arr)
sorted_arr = pigeonhole_sort(arr)
print("Sorted Array:", sorted_arr)
Pigeonhole Sort is a simple and efficient algorithm for specific scenarios involving narrow ranges and integer-based data.
When analyzing a stock, one of the first financial indicators you’ll encounter is EPS, or Earnings Per Share. It’s one… Read More
When you look at a stock’s profile on a financial website, one of the first things you’ll see is its… Read More
In the world of open-source software, simplicity and flexibility are often just as important as legal protection. That’s why the… Read More
If you want your software to be open source, but still compatible with commercial use—and not as restrictive as the… Read More
When it comes to open-source software, developers and businesses alike need licenses that balance freedom, legal clarity, and long-term security.… Read More
If you’re working on open-source projects or choosing third-party libraries for your software, understanding software licenses is essential. Among the… Read More