TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
pigeonhole_sort.cpp
Go to the documentation of this file.
1
16#include <algorithm> //for std::is_sorted
17#include <array> //for std::array
18#include <cassert> //for assert
19#include <iostream> //for io operations
20
25namespace sorting {
26
33template <std::size_t N>
34std::array<int, N> pigeonSort(std::array<int, N> arr) {
35 // Finding min and max*
36 auto min = std::min_element(std::begin(arr), std::end(arr));
37 auto max = std::max_element(std::begin(arr), std::end(arr));
38
39 // Range refers to the number of holes required
40 int range = *max - *min + 1;
41 int *hole = new int[range]();
42
43 // Copying all array values to pigeonhole
44 for (int i = 0; i < N; i++) {
45 hole[arr[i] - *min] = arr[i];
46 }
47
48 // Deleting elements from list and storing to original array
49 int count = 0;
50 for (int i = 0; i < range; i++) {
51 while (hole[i] != '\0') {
52 arr[count] = hole[i];
53 hole[i] = {};
54 count++;
55 }
56 }
57 delete[] hole;
58
59 return arr;
60}
61} // namespace sorting
62
68static void test_1() {
69 const int n = 7;
70 std::array<int, n> test_array = {8, 3, 2, 7, 4, 6, 8};
71
72 test_array = sorting::pigeonSort<n>(test_array);
73
74 assert(std::is_sorted(std::begin(test_array), std::end(test_array)));
75
76 // Printing sorted array
77 for (int i = 0; i < n; i++) {
78 std::cout << test_array.at(i) << " ";
79 }
80 std::cout << "\nPassed\n";
81}
82
88static void test_2() {
89 const int n = 10;
90 std::array<int, n> test_array = {802, 630, 20, 745, 52,
91 300, 612, 932, 78, 187};
92
93 test_array = sorting::pigeonSort<n>(test_array);
94
95 assert(std::is_sorted(std::begin(test_array), std::end(test_array)));
96
97 // Printing sorted array
98 for (int i = 0; i < n; i++) {
99 std::cout << test_array.at(i) << " ";
100 }
101 std::cout << "\nPassed\n";
102}
103
109static void test_3() {
110 const int n = 4;
111 std::array<int, n> test_array = {11, 13, 12, 14};
112
113 test_array = sorting::pigeonSort<n>(test_array);
114
115 assert(std::is_sorted(std::begin(test_array), std::end(test_array)));
116
117 // Printing sorted array
118 for (int i = 0; i < n; i++) {
119 std::cout << test_array.at(i) << " ";
120 }
121 std::cout << "\nPassed\n";
122}
123
127int main() {
128 test_1();
129 test_2();
130 test_3();
131
132 return 0;
133}
for working with vectors
std::array< int, N > pigeonSort(std::array< int, N > arr)
static void test_1()
static void test_2()
int main()
static void test_3()