TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
bogo_sort.cpp
Go to the documentation of this file.
1
17#include <iostream>
18#include <algorithm>
19#include <array>
20#include <cassert>
21#include <random>
22
23
28namespace sorting {
36template <typename T, size_t N>
37std::array <T, N> shuffle (std::array <T, N> arr) {
38 for (int i = 0; i < N; i++) {
39 // Swaps i'th index with random index (less than array size)
40 std::swap(arr[i], arr[std::rand() % N]);
41 }
42 return arr;
43}
51template <typename T, size_t N>
52std::array <T, N> randomized_bogosort (std::array <T, N> arr) {
53 // Untill array is not sorted
54 std::random_device random_device;
55 std::mt19937 generator(random_device());
56 while (!std::is_sorted(arr.begin(), arr.end())) {
57 std::shuffle(arr.begin(), arr.end(), generator);// Shuffle the array
58 }
59 return arr;
60}
61
62} // namespace sorting
63
70template <typename T, size_t N>
71void show_array (const std::array <T, N> &arr) {
72 for (int x : arr) {
73 std::cout << x << ' ';
74 }
75 std::cout << '\n';
76}
77
81void test() {
82 // Test 1
83 std::array <int, 5> arr1;
84 for (int &x : arr1) {
85 x = std::rand() % 100;
86 }
87 std::cout << "Original Array : ";
88 show_array(arr1);
90 std::cout << "Sorted Array : ";
91 show_array(arr1);
92 assert(std::is_sorted(arr1.begin(), arr1.end()));
93 // Test 2
94 std::array <int, 5> arr2;
95 for (int &x : arr2) {
96 x = std::rand() % 100;
97 }
98 std::cout << "Original Array : ";
99 show_array(arr2);
100 arr2 = sorting::randomized_bogosort(arr2);
101 std::cout << "Sorted Array : ";
102 show_array(arr2);
103 assert(std::is_sorted(arr2.begin(), arr2.end()));
104}
105
107int main() {
108 // Testing
109 test();
110 // Example Usage
111 std::array <int, 5> arr = {3, 7, 10, 4, 1}; // Defining array which we want to sort
112 std::cout << "Original Array : ";
113 show_array(arr);
114 arr = sorting::randomized_bogosort(arr); // Callling bogo sort on it
115 std::cout << "Sorted Array : ";
116 show_array(arr); // Printing sorted array
117 return 0;
118}
void test()
Definition bogo_sort.cpp:81
int main()
void show_array(const std::array< T, N > &arr)
Definition bogo_sort.cpp:71
for working with vectors
std::array< T, N > shuffle(std::array< T, N > arr)
Definition bogo_sort.cpp:37
std::array< T, N > randomized_bogosort(std::array< T, N > arr)
Definition bogo_sort.cpp:52