As far as I know, Java is passed by value, i.e. when I work with primitive types I can not swap them (if I worked with Objects, however it would be possible). I wrote a program to write down all permutations of an array of integers. To do this I use a swap
functions that takes as parameters array, two positions, and swap the numbers in these positions. And my program work?! Can somebody explain me why? Below is the code:
public class Solution {
public List<List<Integer>> permute(int[] num) {
if(num == null || num.length == 0)
return null;
List<List<Integer>> res = new ArrayList<List<Integer>>();
doPermute(num, 0, res);
return res;
}
public static void doPermute(int[] num, int k, List<List<Integer>> res){
if(k == num.length){
res.add(convertArrayToList(num));
return;
}
for(int i = k; i < num.length; i++){
swap(num, i, k);
doPermute(num, k+1, res);
swap(num, k, i);
}
}
public static List<Integer> convertArrayToList(int[] num){
List<Integer> res = new ArrayList<Integer>();
for(int i = 0; i < num.length; i++){
res.add(num[i]);
}
return res;
}
public static void swap(int[] num, int i, int j){
int temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}