Description
The Little Elephant enjoys recursive functions.
This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows:
- If x = 1, exit the function.
- Otherwise, call f(x - 1), and then make swap(ax - 1, ax) (swap the x-th and (x - 1)-th elements of a).
The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order.
#include<iostream>
using namespace std;
int a[1005];//此处递归的结构究竟是什么
void f(int n)
{
if(n==1)
return;
else
{
f(n-1);
swap(a[n-2],a[n-1]);//递归调用的本质。注意每次是按顺序执行,执行完f(n-1)才是swap语句
}
}
int main()
{
int n;
cin>>n;
if(n==1)
cout<<n<<endl;
else if(n==2)
cout<<2<<" "<<1<<endl;
else
{
cout<<n<<" ";
a[0]=n;
for(int i=1;i<=n-1;i++)
{
cout<<i<<" ";
a[i]=i;
}
}
cout<<endl;
f(n);
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
}