Next Permutation

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

C++:
01 void nextPermutation(vector<int> &num) {
02       int n=num.size();
03       if(n==0)
04           return;
05       int* A=new int[n];
06       for(int i=0;i<n;i++)
07           A[i]=num[i];
08       next_permutation(A,A+n);
09       for(int i=0;i<n;i++)
10          num[i]=A[i];
11 }

If the STL is not allowed. We can implement this next permutation algorithm.

C++:
01 void swap(vector<int>& num, int a, int b)
02 {
03     int tmp=num[a];
04     num[a]=num[b];
05     num[b]=tmp;
06 }
07 
08 void reverse(vector<int>& num, int a, int b)
09 {
10     for(int i=a,j=b;i<j;i++,j)
11         swap(num,i,j);
12 }
13 
14 void nextPermutation(vector<int> &num) {
15      int i=-1;
16      int t=-1;
17      int n=num.size();
18      if((n==0)||(n==1))
19           return;
20      for(int j=0;j<n1;j++){
21          if(num[j]<num[j+1])
22               i=j;
23      }
24      for(int j=i+1;j<n;j++){
25          if(num[i]<num[j])
26               t=j;
27      }
28      swap(num, i, t);
29      reverse(num,i+1,n1);
30      return;
31 }
Advertisements
This entry was posted in Array and linked list. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s