Languages
[Edit]
EN

Java - random sort array

9 points
Created by:
Efe-V
409

In this short article, we would like to show how in Java, sort array to archive random order.

The below example implements Fisher–Yates shuffle algorithm:

package com.example;

import java.util.Arrays;
import java.util.Random;

public class Program
{
	public static void main(String[] args) throws Exception {

		int[] array = {
			1, 2, 3, 4, 5
		};

		Random random = new Random();

		for (int i = array.length - 1; i > 0; --i) {
			int j = random.nextInt(i);
			int tmp = array[i];
			array[i] = array[j];
			array[j] = tmp;
		}

		System.out.println(Arrays.toString(array));
	}
}

Example output:

[4, 1, 5, 3, 2]

 

Reusable code example

This section contains class prepared co copy as util.

Alternatively, you can use ArrayUtils.shuffle() method provided by Apache Lang library (installation instruction here).

Program.java file:

package com.example;

import java.util.Arrays;

public class Program {

	public static void main(String[] args) throws Exception {

		Integer[] array = {
			1, 2, 3, 4, 5
		};

		ArrayUtils.shuffle(array);

		System.out.println(Arrays.toString(array));
	}
}

ArrayUtils.java file:

package com.example;

import java.util.Random;

public class ArrayUtils {

    public static <T> void shuffle(T[] array) {
        Random random = new Random();
        for (int i = array.length - 1; i > 0; --i) {
            int j = random.nextInt(i);
            T tmp = array[i];
            array[i] = array[j];
            array[j] = tmp;
        }
    }
}

References

  1. Fisher–Yates shuffle - Wikipedia

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join