Shuffle the array elements

Shuffling is a procedure used to randomize an array element. Similar way suppose we are given an array which contains n elements. Our goal is to randomize the elements of this array in efficient manner. Lets see few examples.

Example 1
arr = [1 , 0 , -3 , 8 , 7 , 3 , 9 , 4 , 2 , 5 , 10 , 6]
// Shuffle array
Output
      [6,  -3,  5,  9,  2,  7,  0,  4,  3,  8,  1,  10]
      [10,  7,  1,  2,  9,  -3,  3,  5,  0,  6,  8,  4]
      [4,  2,  5,  6,  1,  -3,  7,  3,  0,  10,  8,  9]
      etc
-------------------------

Example 2
arr = ['a',  'b',  'c',  'x',  'y',  'z']
output
      ['z',  'y',  'b',  'x',  'a',  'c']
      ['z',  'b',  'x',  'y',  'a',  'c']
      ['x',  'b',  'a',  'c',  'y',  'z']
      etc

Result can be any order in given array and result are modified (reflect) to actual array. There can be many ways to do this work, but the effective way is to swap elements and change the order. In the example below, the approach of finding a random index and swapping its element is implementing.

Time complexity analysis in above solution is O(n), n indicates number of array elements. And may be resulting array is similar to given array (But that is very rarely).



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







© 2021, kalkicode.com, All rights reserved