Here you can find the source of nextPermutation(int[] arr)
Parameter | Description |
---|---|
arr | a parameter |
public static int[] nextPermutation(int[] arr)
//package com.java2s; public class Main { /**//from ww w .j a va 2 s. c o m * @param arr * @return */ public static int[] nextPermutation(int[] arr) { int[] a = (int[]) arr.clone(); int n = a.length - 1; int j = n - 1; // "123, 132, 213, 231, 312, 321" while (a[j] > a[j + 1]) { if (j == 0) { // last permutation - reset int[] error = new int[] { 0 }; return error; } j--; } // j is the largest subscript with a[j] < a[j+1] int k = n; while (a[j] > a[k]) { // sanity checking here k--; } // a[k] is the smallest term greater than a[j] to the // right of a[j] -- swap a[j] and a[k] int tmp = a[j]; a[j] = a[k]; a[k] = tmp; int r = n; int s = j + 1; while (r > s) { // swap a[r] and a[s] tmp = a[r]; a[r] = a[s]; a[s] = tmp; r--; s++; } return a; } }