Created
August 20, 2024 01:46
-
-
Save dqtweb/56c596c8acbc4053e836cd560890494b to your computer and use it in GitHub Desktop.
Fisher-Yates algorithm (or Knuth Shuffle)
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 static List<Object> shuffleList(List<Object> list) { | |
Random rand = new Random(); | |
// convert to array | |
Object[] array = list.toArray(); | |
for (int i = array.length - 1; i > 0; i--) { | |
// generate random number in range 0 to i | |
int j = rand.nextInt(i + 1); | |
// swap array[i] with array[j] | |
Object temp = array[i]; | |
array[i] = array[j]; | |
array[j] = temp; | |
} | |
// convert back to list | |
return Arrays.asList(array); | |
} |
Author
dqtweb
commented
Aug 20, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment