In this program, we are going to share Java Program to shuffle a given array with the output. If you are a Java beginner and want to start learning the Java programming, then keep your close attention in this tutorial as I am going to share how to write a java program to shuffle a given array.
Copy the below Java program and execute it with the help of Javac compiler. At the end of this program, We have shared the output of this program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.util.Random; import java.util.Arrays; public class ShuffleRand { static void randomize( int arr[], int n) { Random r = new Random(); for (int i = n-1; i > 0; i--) { int j = r.nextInt(i); int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } System.out.println(Arrays.toString(arr)); } public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5, 6, 7, 8}; int n = arr.length; randomize (arr, n); } } |
7 8 4 6 3 1 2 5
Liked this program? Do Like & share with your friends.
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.