Randomly Sort an Array in Java

How to quickly, randomly sort an array in Java:

for(int i = array.length-1; i > 1 ; i--) {
        randIndex = random.nextInt(i);
        temp = array[i];
        array[i] = array[randIndex];
        array[randIndex] = temp;
}

Note: You will need to declare “randIndex” as int, “temp” as the same type as the array’s members, and “random” as new java.util.Random().

How it works: The “for” loop starts at end of array and moves towards the beginning. The variable “i” acts as a cursor separating the randomized end of the array from the un-randomized beginning of the array. The next line takes some int value representing a random space up to end of unsorted area. The value of current unsorted letter (at the cursor “i”) is then stored within “temp” and the random letter is set to the value of the current un-randomized space. Finally, the value of unsorted letter is restored to original random space.


Follow

Get every new post delivered to your Inbox.

Join 45 other followers