Guest User

Untitled

a guest
Jul 17th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. import java.util.Arrays;
  2. import java.util.Scanner;
  3.  
  4. public class LC_31_2 {
  5. public static void main(){
  6. Scanner sc = new Scanner(System.in);
  7. int numDigit = sc.nextInt();
  8. int[] arr = new int[numDigit];
  9. for(int i = 0; i < numDigit; i++){
  10. arr[i] = sc.nextInt();
  11. }
  12. System.out.println("Before Pemutation:");
  13. System.out.println(Arrays.toString(arr));
  14.  
  15. System.out.println();
  16. System.out.println();
  17.  
  18. System.out.println("After Permutation");
  19.  
  20. nextPermutation(arr);
  21.  
  22. System.out.println(Arrays.toString(arr));
  23.  
  24.  
  25. }
  26.  
  27. public static void nextPermutation(int[] nums) {
  28.  
  29. //[9, 5, 4, 8, 7, 6, 3, 2, 1]
  30. // i i+1
  31. //
  32.  
  33. int i = nums.length - 2;
  34.  
  35. while( i >= 0 && nums[i] > nums[i + 1] ){
  36. i--;
  37. }
  38.  
  39.  
  40. //[9, 5, 4, 8, 7, 6, 3, 2, 1]
  41. // i j
  42. //
  43.  
  44. int j = nums.length - 1;
  45.  
  46. while(i < j && nums[j] < nums[i] ){
  47. j--;
  48. }
  49.  
  50. //System.out.println("i with index " + i + ", nums[i]=" + nums[i] );
  51. // System.out.println("j with index " + j + ", nums[j]=" + nums[j] );
  52. // i found at index 2 with value 4!!!
  53.  
  54.  
  55. //[9, 5, 4, 8, 7, 6, 3, 2, 1]
  56. // i j
  57. //
  58.  
  59. // swap nums[i] with nums[j]
  60. swap(nums , i , j);
  61.  
  62.  
  63. //[9, 5, 6, 8, 7, 4, 3, 2, 1]
  64. // i j
  65. //
  66.  
  67. // reverse from (i+1) ~~~ end
  68.  
  69.  
  70. reverse(nums, i + 1 , nums.length - 1 );
  71. }
  72.  
  73. private static void reverse(int[] nums, int start, int end){
  74. //[9, 5, 6, 8, 7, 4, 3, 2, 1]
  75. // i j
  76. // st end
  77.  
  78. //[9, 5, 6, 1, 7, 4, 3, 2, 8]
  79. // i j
  80. // st end
  81. while(start < end){
  82. swap(nums, start , end);
  83. start++;
  84. end--;
  85. }
  86. }
  87.  
  88. private static void swap(int[] nums, int i, int j){
  89. int temp = nums[i];
  90. nums[i] = nums[j];
  91. nums[j] = temp;
  92. }
  93. }
Add Comment
Please, Sign In to add comment