fork(2) download
  1. class NextPermutation {
  2.  
  3. public static void nextPermutation(int[] num) {
  4. int n = num.length;
  5. if (n < 2)
  6. return;
  7. int index = n - 1;
  8. while (index > 0) {
  9. if (num[index - 1] < num[index])
  10. break;
  11. index--;
  12. }
  13. if (index == 0) {
  14. reverseSort(num, 0, n - 1);
  15. return;
  16. } else {
  17. int val = num[index - 1];
  18. int j = n - 1;
  19. while (j >= index) {
  20. if (num[j] > val)
  21. break;
  22. j--;
  23. }
  24. swap(num, j, index - 1);
  25. reverseSort(num, index, n - 1);
  26. return;
  27. }
  28. }
  29.  
  30. public static void swap(int[] num, int i, int j) {
  31. int temp = 0;
  32. temp = num[i];
  33. num[i] = num[j];
  34. num[j] = temp;
  35. }
  36.  
  37. public static void reverseSort(int[] num, int start, int end) {
  38. if (start > end)
  39. return;
  40. for (int i = start; i <= (end + start) / 2; i++)
  41. swap(num, i, start + end - i);
  42. }
  43.  
  44. public static void main(String[] args) {
  45. String s = "abc";
  46. int[] x = new int[s.length()];
  47. for (int i = 0; i < s.length(); i++) {
  48. x[i] = s.charAt(i);
  49. }
  50. nextPermutation(x);
  51.  
  52. for (int i : x) {
  53. System.out.print((char) i);
  54. }
  55. }
  56. }
  57.  
Success #stdin #stdout 0.04s 4386816KB
stdin
Standard input is empty
stdout
acb