EMChamp Blog

Coding Problem 4 | Shuffle Int Array

Another fairly common problem. Main challenge that I see would be generating the random integer. I chose to do this in place, its possible to do it out of place too but in my opinion the in place solution is more natural to this sort of problem not to mention it has O(1) space complexity. My algorithm was:

for each element in array:
1) Generate the random index for the element that you will swap with the current element.
2) Save the current element index in a temp variable because we are going to ovewrite it with the element from the random index.
3) Copy the random element into the current element thus overwriting the value of the current element, however the value is saved in step 2.
4) Copy saved value of current element into the random element thus completing the swap of the current element and the random element.

return original array which was swapped in place.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

import java.util.Random;


public class ArrayShuffleCalc {

public int[] shuffleArray(int[] testArray) {
Random randomInt = new Random();
for(int i = 0; i < testArray.length; i++) {
int tempIndex = randomInt.nextInt(testArray.length-1);
int tempInt = testArray[i];
testArray[i] = testArray[tempIndex];
testArray[tempIndex] = tempInt;
}
return testArray;
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13

public class ArrayShuffleDriver {

public static void main(String[] args) {
int[] testIntArray = {1,2,3,4,5,6,7,8,9,10};

ArrayShuffleCalc basicShuffle = new ArrayShuffleCalc();

System.out.println(Arrays.toString(basicShuffle.shuffleArray((testIntArray))));
}

}