Last active
April 10, 2016 07:18
-
-
Save srajappa/23b241b5e4a7218dbaefbf954dc568de to your computer and use it in GitHub Desktop.
Finds all permutations of a list containing distinct integers.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ListOperations { | |
public void nextPermutation(int[] nums) { | |
int nonDecIdx=nums.length-1; | |
//int[] result; | |
if(nums.length==1) | |
return; | |
while(nonDecIdx > 0){ | |
if(nums[nonDecIdx] > nums[nonDecIdx-1]) | |
break; | |
nonDecIdx--; | |
} | |
//System.out.println("nondec "+nonDecIdx+" nums,lght "+(nums.length-1) ); | |
if(nonDecIdx == 0){ | |
performSpReverse(nums,0,nums.length-1); | |
return; | |
}else{ | |
int swapW = nums[nonDecIdx-1]; | |
for(int i=nums.length-1; i >= nonDecIdx; i--){ | |
if(swapW < nums[i]){ | |
performSpSwap(nums,nonDecIdx-1,i); | |
//Collections.swap(Arrays.asList(nums),nonDecIdx-1, i); | |
break; | |
} | |
} | |
//Reverse the sub array | |
performSpReverse(nums,nonDecIdx,nums.length-1); | |
} | |
return; | |
} | |
public void performSpReverse(int[] nums, int left, int right){ | |
while(left<=right){ | |
//Collections.swap(Arrays.asList(nums),left,right); | |
performSpSwap(nums,left,right); | |
left++; | |
right--; | |
} | |
} | |
public void performSpSwap(int[] nums, int left, int right){ | |
int temp; | |
temp = nums[left]; | |
nums[left] = nums[right]; | |
nums[right] = temp; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment