forked from iiitu-force/Hacktoberfest-2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pigeonhole_sort.java
50 lines (37 loc) · 1.02 KB
/
pigeonhole_sort.java
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
import java.lang.*;
import java.util.*;
public class pigeonhole_sort
{
public static void pigeonhole_sort(int arr[],
int n)
{
int min = arr[0];
int max = arr[0];
int range, i, j, index;
for(int a=0; a<n; a++)
{
if(arr[a] > max)
max = arr[a];
if(arr[a] < min)
min = arr[a];
}
range = max - min + 1;
int[] phole = new int[range];
Arrays.fill(phole, 0);
for(i = 0; i<n; i++)
phole[arr[i] - min]++;
index = 0;
for(j = 0; j<range; j++)
while(phole[j]-->0)
arr[index++]=j+min;
}
public static void main(String[] args)
{
GFG sort = new GFG();
int[] arr = {8, 3, 2, 7, 4, 6, 8};
System.out.print("Sorted order is : ");
sort.pigeonhole_sort(arr,arr.length);
for(int i=0 ; i<arr.length ; i++)
System.out.print(arr[i] + " ");
}
}