1. From the last index, we seach the first decrease order, such i,i+1 and num[i]<num[i+1]
2. From the last index to i+1, we search the first element which is larger than num[i], such as k, swap(i,k)
3. Swap the element from i+1 to the last one, namely to sort them to increase order(left to right viewpoint)
Take an example.
13542
The first decrease order is 35
then search the first element from right to left which is larger than 3, get 4, swap 3 and 4
13542 -> 14532 -> 14235
The last step is to change the order from 5 to 2 to be increase order.
1 /* 2 Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. 3 4 If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). 5 6 The replacement must be in-place, do not allocate extra memory. 7 8 Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. 9 1,2,3 → 1,3,210 3,2,1 → 1,2,311 1,1,5 → 1,5,112 13 */14 15 public class Solution {16 public void nextPermutation(int[] nums) {17 //search for the first decrease order,from right to left-hand18 int i=nums.length-1;19 for(;i>0;i--){20 if(nums[i]>nums[i-1]){21 break;22 }23 }24 //if there is no decrease order, just return the increase order25 if(i==0){26 Arrays.sort(nums);27 return;28 }29 i--;30 int j=nums.length-1;31 for(;j>=0;j--){32 if(nums[j]>nums[i]){ //get it here33 int tmp = nums[j];34 nums[j]=nums[i];35 nums[i]=tmp;36 break;37 }38 }39 //swap40 int begin=i+1;41 int end=nums.length-1;42 while(begin