Pancake sorting: chỉ được phép đảo ngược tiền tố mảng. Mục tiêu sắp xếp tăng dần với ít lần đảo nhất.
Ví dụ
Input: 5 3 2 1 4
Output: 1 2 3 4 5
Chương trình C++ ví dụ
#include <iostream>
using namespace std;
void do_flip(int *list, int length, int num) {
for(int i=0;i<--num;i++) swap(list[i], list[num]);
}
int pancake_sort(int *list, unsigned int length) {
if (length<2) return 0;
int moves=0;
for(int i=length;i>1;i--) {
int max_pos=0;
for(int a=0;alist[max_pos]) max_pos=a;
if(max_pos==i-1) continue;
if(max_pos) { moves++; do_flip(list,length,max_pos+1); }
do_flip(list,length,i); moves++;
}
return moves;
}
int main() {
int arr[]={5,3,2,1,4}, n=5;
int moves=pancake_sort(arr,n);
for(int i=0;i