TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
pancake_sort.cpp
Go to the documentation of this file.
1
19#include <algorithm> // for std::is_sorted
20#include <cassert> // for std::assert
21#include <iostream> // for io operations
22#include <vector> // for std::vector
23
28namespace sorting {
34namespace pancake_sort {
42template <typename T>
43void reverse(std::vector<T> &arr, int start, int end) {
44 T temp; // Temporary variable
45 while (start <= end) {
46 temp = arr[start];
47 arr[start] = arr[end];
48 arr[end] = temp;
49 start++;
50 end--;
51 }
52}
60template <typename T>
61int pancakeSort(std::vector<T> &arr, int size) {
62 for (int i = size; i > 1; --i) {
63 int max_index = 0, j = 0; // intialize some variables.
64 T max_value = 0;
65 for (j = 0; j < i; j++) {
66 if (arr[j] >= max_value) {
67 max_value = arr[j];
68 max_index = j;
69 }
70 }
71 if (max_index != i - 1) // check for reversing
72 {
73 reverse(arr, 0, max_index);
74 reverse(arr, 0, i - 1);
75 }
76 }
77 return 0;
78}
79} // namespace pancake_sort
80} // namespace sorting
81
86static void test() {
87 // example 1: vector of int
88 const int size1 = 7;
89 std::cout << "\nTest 1- as std::vector<int>...";
90 std::vector<int> arr1 = {23, 10, 20, 11, 12, 6, 7};
91 sorting::pancake_sort::pancakeSort(arr1, size1);
92 assert(std::is_sorted(arr1.begin(), arr1.end()));
93 std::cout << "Passed\n";
94 for (int i = 0; i < size1; i++) {
95 std::cout << arr1[i] << " ,";
96 }
97 std::cout << std::endl;
98
99 // example 2: vector of double
100 const int size2 = 8;
101 std::cout << "\nTest 2- as std::vector<double>...";
102 std::vector<double> arr2 = {23.56, 10.62, 200.78, 111.484,
103 3.9, 1.2, 61.77, 79.6};
104 sorting::pancake_sort::pancakeSort(arr2, size2);
105 assert(std::is_sorted(arr2.begin(), arr2.end()));
106 std::cout << "Passed\n";
107 for (int i = 0; i < size2; i++) {
108 std::cout << arr2[i] << ", ";
109 }
110 std::cout << std::endl;
111
112 // example 3:vector of float
113 const int size3 = 7;
114 std::cout << "\nTest 3- as std::vector<float>...";
115 std::vector<float> arr3 = {6.56, 12.62, 200.78, 768.484, 19.27, 68.87, 9.6};
116 sorting::pancake_sort::pancakeSort(arr3, size3);
117 assert(std::is_sorted(arr3.begin(), arr3.end()));
118 std::cout << "Passed\n";
119 for (int i = 0; i < size3; i++) {
120 std::cout << arr3[i] << ", ";
121 }
122 std::cout << std::endl;
123}
128int main() {
129 test();
130 return 0;
131}
Functions for Pancake sort algorithm.
for working with vectors
static void test()
Test implementations.
int pancakeSort(std::vector< T > &arr, int size)
This implementation is for a C-style array input that gets modified in place.
int main()
Main function.