Java Integer Array Permutation nextPermutation(int[] nums)

Here you can find the source of nextPermutation(int[] nums)

Description

next Permutation

License

Apache License

Declaration

public static void nextPermutation(int[] nums) 

Method Source Code

//package com.java2s;
/*/*from w ww. j av  a2 s . com*/
 *    Copyright 2015 Lee Yik Jiun
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

public class Main {
    public static void nextPermutation(int[] nums) {
        int n = nums.length;
        int i;
        for (i = n - 2; i >= 0; --i) {
            if (nums[i] < nums[i + 1]) {
                break;
            }
        }
        if (i < 0) {
            return;
        }
        int j;
        for (j = n - 1; j > i; --j) {
            if (nums[i] < nums[j]) {
                break;
            }
        }
        swap(nums, i, j);
        reverse(nums, i + 1);
    }

    private static void swap(int[] nums, int i, int j) {
        int t = nums[i];
        nums[i] = nums[j];
        nums[j] = t;
    }

    /**
     * Reverses an array
     *
     * Time: O(n)
     * Space: O(1)
     * where n is the number of elements in the array.
     */
    public static void reverse(int[] nums) {
        reverse(nums, 0);
    }

    /**
     * Reverses an array.
     *
     * Time: O(n)
     * Space: O(1)
     * where n is the number of elements in the array.
     * @param beginIndex the begin index, inclusive.
     */
    public static void reverse(int[] nums, int beginIndex) {
        reverse(nums, beginIndex, nums.length);
    }

    /**
     * Reverses an array.
     *
     * Time: O(n)
     * Space: O(1)
     * where n is the number of elements in the array.
     * @param beginIndex the begin index, inclusive.
     * @param endIndex the end index, exclusive.
     */
    public static void reverse(int[] nums, int beginIndex, int endIndex) {
        int i = beginIndex;
        int j = endIndex - 1;

        while (i < j) {
            swap(nums, i++, j--);
        }
    }
}

Related

  1. nextPermutation(int v)
  2. nextPermutation(int[] arr)
  3. nextPermutation(int[] is)
  4. nextPermutation(int[] next)