-
Notifications
You must be signed in to change notification settings - Fork 367
Expand file tree
/
Copy pathpigeonhole sort.java
More file actions
53 lines (43 loc) · 1.29 KB
/
pigeonhole sort.java
File metadata and controls
53 lines (43 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import java.util.Scanner;
public class PigeonholeSortExample {
public static void pigeonholeSort(int[] arr) {
int min = arr[0], max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
}
if (arr[i] > max) {
max = arr[i];
}
}
int range = max - min + 1;
int[] pigeonholes = new int[range];
for (int i = 0; i < arr.length; i++) {
pigeonholes[arr[i] - min]++;
}
int index = 0;
for (int i = 0; i < range; i++) {
while (pigeonholes[i] > 0) {
arr[index++] = i + min;
pigeonholes[i]--;
}
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("Enter the elements:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
pigeonholeSort(arr);
System.out.print("Sorted array: ");
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
}