File tree 1 file changed +47
-0
lines changed
sortingAlgo/pigeonholeSort
1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Pigeonhole Sort in C++
2
+ #include < bits/stdc++.h>
3
+ using namespace std ;
4
+
5
+ void pigeonhole_sort (int arr[], int n)
6
+ {
7
+ int minn = *min_element (arr, arr+ n) ;
8
+ int maks = *max_element (arr, arr+ n) ;
9
+
10
+ int range = maks - minn + 1 ;
11
+
12
+ vector<int > holes[range];
13
+
14
+ for (int i = 0 ; i < n; i++)
15
+ holes[arr[i]-minn].push_back (arr[i]);
16
+
17
+ int j = 0 ;
18
+ for (int i = 0 ; i < range; i++)
19
+ {
20
+ for (int k = 0 ; k < holes[i].size () ; k++)
21
+ {
22
+ arr[j] = holes[i][k] ;
23
+ j++ ;
24
+ }
25
+ }
26
+ }
27
+
28
+ int main ()
29
+ {
30
+ int n ; cin >> n ;
31
+ int a[n] ;
32
+ for (int i = 0 ; i < n ; i ++) cin >> a[i] ;
33
+
34
+ pigeonhole_sort (a , n) ;
35
+
36
+
37
+ for (int i = 0 ; i < n ; i++) cout << a[i] << " " ;
38
+ }
39
+
40
+ /* here n is the number of elements in the array to be sorted and a[0...n-1] is the array.
41
+ input example:
42
+ 5
43
+ 5 4 3 2 1
44
+ Output:
45
+ 1 2 3 4 5
46
+ Length of the range of possible key values = N; number of elements in the array =n;
47
+ Overall time complexity = O(n+N) ; Overall Space complexity = O(N) */
You can’t perform that action at this time.
0 commit comments