java next_permutation

public static boolean next_permutation(int[] arr) {
	int len = arr.length;
	int i = len - 1;

    // 1. find largest i where arr[i - 1] < arr[i]
	while (i > 0) {
		if (arr[i - 1] < arr[i]) break;
    	i--;
  	}

  	if (i <= 0) return false;

  	// 2. find largest j where arr[i - 1] < arr[j] and j >= i
  	int j = len - 1;
  	while (j >= i) {
    	if (arr[i - 1] < arr[j]) break;
    	j--;
  	}

	// 3. swap elements between arr[i-1] and arr[j]
  	swap(i - 1, j, arr);

  	// 4. reverse elements from i to end of array
  	len--;
  	while (i < len) {
    	swap(i, len, arr);
    	len--;
    	i++;
  	}
  	return true;
}

public static void swap(int x, int y, int[] arr) {
  	int temp = arr[x];
  	arr[x] = arr[y];
  	arr[y] = temp;
}

Are there any code examples left?
Create a Free Account
Unlock the power of data and AI by diving into Python, ChatGPT, SQL, Power BI, and beyond.
Sign up
Develop soft skills on BrainApps
Complete the IQ Test
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source