Array: Randomly shuffle the elements of an array

Q) Randomly shuffle the elements of an array

Example

Original Array: 2,5,1,7,8,2

Output 1:
5 2 8 1 2 7

Output 2:
5 1 8 2 2 7

package Array;

/**
 * Created by aarushi on 24/4/21.
 */
public class ArrayRandomShuffle {

    public static void randomShuffle (int [] array){
        for (int i=array.length-1; i>=0; i--){
          	//randomly generate an index from 0 to i 
            int randIndex= (int)(Math.random()*i);
          	//swap elements
            int temp= array[i];
            array[i]=array[randIndex];
            array[randIndex]= temp;
        }
    }

    public static void main (String [] args){
        int [] array= {2,5,1,7,8,2};
        randomShuffle(array);
      	for (int i=0; i<array.length; i++){
          System.out.print(array[i]+ " ");
        }
    }

}

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close