Shuffle the array elements
The problem is to shuffle the elements of an array randomly. Shuffling an array means rearranging its elements in a random order. The goal is to achieve a random permutation of the array elements.
Example
Consider the following array:
[1, 0, 3, 8, 7, 3, 9, 4, 2, 5, 10, 6]
After shuffling, the array may become:
[2, 8, 0, 4, 7, 3, 6, 10, 9, 5, 1, 3]
or
[3, 10, 6, 7, 4, 2, 1, 9, 0, 8, 5, 3]
or
[2, 7, 6, 5, 3, 0, 10, 9, 3, 4, 8, 1]
and so on.
Idea to Solve the Problem
To shuffle the array elements, we can use a simple approach known as the FisherYates shuffle algorithm. The
algorithm works by iterating through the array from the last element to the second element. For each element at
index i
, it randomly selects an index j
between 0
and i
(inclusive) and swaps the elements at indices i
and j
.
Algorithm (FisherYates Shuffle)
 Start from the last element of the array and go up to the second element.
 For each element at index
i
, generate a random indexj
between0
andi
.  Swap the elements at indices
i
andj
.
Pseudocode
function shuffle(arr):
size = length of arr
for i from size  1 to 1:
j = random location between 0 and i
swap arr[i] with arr[j]
end for
end function
Code Solution

1) Shuffle the elements of array in java
2) Shuffle the elements of array in c#
3) Shuffle an array in node js
4) Shuffle an array in python
5) Shuffle an array in ruby
6) Shuffle an array in scala
7) Shuffle an array in swift
8) Shuffle an array in kotlin
9) Shuffle an array in c
10) Shuffle an array in c++
11) Shuffle an array in golang
12) Shuffle the elements of array in vb.net
13) Shuffle the elements of array in php
Time Complexity
 The time complexity of the FisherYates shuffle algorithm is O(N), where N is the number of elements in the array. This is because we iterate through the array once, and for each iteration, we perform a constanttime swap operation.
 Therefore, the overall time complexity of the shuffling algorithm is O(N), making it efficient for large arrays.
Resultant Output Explanation
The given Java program implements the FisherYates shuffle algorithm to shuffle the array elements. It starts with an array of integer elements and shuffles the elements multiple times. The output displays the initial array elements before shuffling and the array elements after shuffling.
In the provided output, the initial array is [1, 0, 3, 8, 7, 3, 9, 4, 2, 5, 10, 6]
. After each
shuffle, the array elements are rearranged in a random order. The program executes the shuffle operation
multiple times to show different possible shuffling outcomes. The final output displays the shuffled arrays.
Note: The specific order of the shuffled elements may vary each time the program is executed, as the shuffling is random.
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment