C++ Pancake sort Exercise: Sort a collection of integers using the Pancake sort
C++ Sorting: Exercise-11 with Solution
Write a C++ program to sort a collection of integers using the Pancake sort.
Sample Solution:
C++ Code :
//Ref: https://bit.ly/2rcvXK5
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
// pancake sort template (calls predicate to determine order)
template <typename BidIt, typename Pred>
void pancake_sort(BidIt first, BidIt last, Pred order)
{
if (std::distance(first, last) < 2) return; // no sort needed
for (; first != last; --last)
{
BidIt mid = std::max_element(first, last, order);
if (mid == last - 1)
{
continue; // no flips needed
}
if (first != mid)
{
std::reverse(first, mid + 1); // flip element to front
}
std::reverse(first, last); // flip front to final position
}
}
// pancake sort template (ascending order)
template <typename BidIt>
void pancake_sort(BidIt first, BidIt last)
{
pancake_sort(first, last, std::less<typename std::iterator_traits<BidIt>::value_type>());
}
int main()
{
std::vector<int> data;
data = {125, 0, 695, 3, -256, -5, 214, 44, 55};
std::cout << "Original numbers:\n";
std::copy(data.begin(), data.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
pancake_sort(data.begin(), data.end()); // ascending pancake sort
std::cout << "Sorted numbers:\n";
std::copy(data.begin(), data.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}
Sample Output:
Original numbers: 125 0 695 3 -256 -5 214 44 55 Sorted numbers: -256 -5 0 3 44 55 125 214 695
Flowchart:
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C++ program to sort a collection of integers using the Merge sort.
Next: Write a C++ program to sort a collection of integers using the Quick sort.
What is the difficulty level of this exercise?