/*mplement 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,23,2,1 → 1,2,31,1,5 → 1,5,1 gives the next dictionary order for the array, and if it does not, prints the ascending sequence of the arrays */public class solution { public void nextpermutation (Int[] a) { /* from tail to head, find the first number a[flag]<a[flag+1] For example 1 5 8 7 4 , found 5. If not found, directly output the entire array after ordering the sequence. find the smallest one of the largest numbers after flag for the first one larger than A[flag], */ if (a==null| | A.length==1) { return; } int len=a.length; int flag=-1; // From the back forward to find the start down to the position. for (int i=len-1;i>0;i--) { if (A[i-1]<a[i]) { flag=i-1; break; } } if (flag==-1) { /* not found, indicating that the entire array is in reverse order, It is ok to sort the array directly from the new. below can actually not fast platoon, because already knew reverse order. Direct end-to-end exchange on Ok*/ partsort (a,0,len-1); return ; }else{ //found the flag, sorted the array after the flag, sorted the exchange first than A[flag] Large numbers with A[flag] partsort (a,flag+1,len-1); for (int i=flag+1;i<=len-1;i++) { &nbsP; if (A[i]>a[flag]) {//Exchange int tmp=a[i]; a[i]=a[flag]; a[flag]=tmp; return; } } } return ; } //sorting of the fast rows, sorting the fixed parts of the array private void Partsort (int arr[], int left, int right) { //digging pit fill if (left>=right) { return; } int flag=arr[left]; int i=left; int j=right; while (I<J) { while (ARR[J]&NBSP;>=&NBSP;FLAG&NBSP;&&&NBSP;I&NBSP;<&NBSP;J) { j--; } //So after the swap is over, you need to find a position for the first datum element, which is where I is now . while (ARR[I]&NBSP;<=&NBSP;FLAG&NBSP;&&&NBSP;I&NBSP;<&NBSP;J) { i++; } if (I&NBSP;<&NBSP;J) { swap (ARR,&NBSP;I,&NBSP;J); } } swap (arr, left, i); partsort ( arr, left, i - 1); partsort (arr,i+1,right); } private void swap (INT[]&NBSP;ARR,INT&NBSP;I,INT&NBSP;J) { int temp =arr[i]; arr[i ] = arr[j]; arr[j] = temp; }}
Leetcode/next permutation